我经常面临一个错误:未定义的对象不是一个对象(计算'state.markers'),这很奇怪,我不知道我为什么一直这么做。
以下是我的代码:
function ExploreScreen() {
const handleUserLocation = () => {
navigator.geolocation.getCurrentPosition((pos) => {
const newMapState = {
markers,
categories: [
{
name: "Nearby Events",
icon: (
<MaterialCommunityIcons
style={styles.chipsIcon}
name="near-me"
size={18}
/>
),
},
],
region: {
latitude: pos.coords.latitude,
longitude: pos.coords.longitude,
latitudeDelta: 0.04864195044303443,
longitudeDelta: 0.040142817690068,
},
};
alert(JSON.stringify(pos));
});
};
const [state, setState] = React.useState(handleUserLocation);
let mapIndex = 0;
...呈现功能:(这只是一个较短版本的代码,我不得不删除大量显示,我可以在这里发布)
return (
<>
<Screen style={styles.screen}>
<MapView
ref={_map}
initialRegion={region}
style={styles.container}
>
//some code go here
</MapView>发布于 2021-01-12 00:36:40
您可以按照useState的文档传递一个函数。但是,请注意,不能使用异步函数-它必须立即返回状态。正如docs所言,当计算初始状态时,它被认为是昂贵的,并且您不希望每次呈现组件时都不必要地这样做。
问题是您需要从该函数返回初始状态。您不是这样做的-您是从该函数返回undefined,并在回调中执行一些操作。重写整件事。
用词:
region保持为单独的状态。代码:
function ExploreScreen() {
const [region,setRegion] = useState(undefined);
const [state,setState] = useState({
markers:[],
categories:{
name: "Nearby Events",
icon: (
<MaterialCommunityIcons
style={styles.chipsIcon}
name="near-me"
size={18}
/>
),
}
});
useEffect(() {
// on mount fetch the position and set the state
navigator.geolocation.getPosition(pos => {
setRegion(...whatever you want);
});
},[]);
// after this, your effects should have a dependency of region AND/OR state.markers
}https://stackoverflow.com/questions/65676183
复制相似问题