我在使用 React Hooks 时遇到了 useContext 方法的问题。我的 MapStyle 上下文类(使用 Google Maps API)如下:
import React, { createContext, useState } from 'react';
const MapStyleContext = createContext();
function MapStyleProvider(props) {
const [selectedMapStyle, setSelectedMapStyle] = useState();
return (
<MapStyleContext.Provider value={{ selectedMapStyle, setSelectedMapStyle}}>
{props.children}
</MapStyleContext.Provider>
);
}
export { MapStyleContext, MapStyleProvider };
我有 map 组件试图访问 selectedMapStyle 属性:
...
export default function Map() {
const { isLoaded, loadError } = useLoadScript({
googleMapsApiKey: process.env.REACT_APP_MAPS_API_KEY
});
const { selectedMapStyle } = useContext(MapStyleContext);
...
最后,在 MapStyle 组件中,我尝试在用户更改单选按钮的值时使用 setter setSelectedMapStyle:
import React, { useContext } from 'react';
import { Card, CardBody, Button, FormGroup, Label, Input } from 'reactstrap';
import { MenuContext } from '../../MenuContext';
import { MapStyleContext } from '../mapStyle/MapStyleContext'
import '../Tool.css';
export default function MapStyle() {
const {setSelectedItem} = useContext(MenuContext);
const {setSelectedMapStyle} = useContext(MapStyleContext);
const mapStyles = [
{ 'label': 'Map (default)', 'value': 'default' },
{ 'label': 'Grayscale (Clean)', 'value': 'cleanGray' },
{ 'label': 'Subtle Grayscale', 'value': 'subtleGray' },
{ 'label': 'Ultra light', 'value': 'ultralight' },
{ 'label': 'Clean (no labels)', 'value': 'cleanNoLabel' },
{ 'label': 'Clean (roads)', 'value': 'cleanRoads' }
];
return (
<div className="tool">
<Card>
<CardBody>
<div className="clearfix">
<h3 className="float-left mb-0 mr-2">Map Style</h3>
<Button onClick={() => setSelectedItem(null)} className="float-right" close />
</div>
<hr />
<FormGroup tag="fieldset">
{mapStyles.map(mapStyle => (
<FormGroup key={mapStyle.value} check>
<Label check>
<Input type='radio' name='mapStyle' value={mapStyle.value} onChange={setSelectedMapStyle(mapStyle.value)}/>
{mapStyle.label}
</Label>
</FormGroup>
))}
</FormGroup>
</CardBody>
</Card>
</div>
);
}
我不太确定我哪里出错了,但是当我使用这个上下文时,上下文 Prop 似乎永远不会正确加载(给我类型错误)。
最佳答案
您在这里遇到的问题是 useContext(MapStyleContext)
的值在初始化时为空,并且您从未将父组件或当前组件包装在 中上下文提供者
。
这是一个例子:
function Map() {
return (
<Context.Provider>
{/*children */}
<Context.Provider>
);
}
关于javascript - '类型错误 : Right side of assignment cannot be destructured' useContext React Hooks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64326598/