[英]React Native Variable Undefined
Im not understanding why my varaible is undefined, i firstly declare my variable geojsonData as a let so i am able to change the values later in the code.我不明白为什么我的变量是未定义的,我首先将我的变量 geojsonData 声明为一个 let,这样我就可以稍后在代码中更改这些值。 In my useEffect where i use an if statement to check if check if the visibility is true, i set my geojsonData's value.
在我使用 if 语句检查可见性是否为真的 useEffect 中,我设置了 geojsonData 的值。 However, in the return of the function my values are not set.
但是,在 function 的返回中,我的值没有设置。
Is there a way i can set the geojson data?有没有办法可以设置geojson数据?
let geojsonData;
...
useEffect(() => {
if(componentVisible == true){
geojsonData = {
type: Type,
features: [
{
type: featuresType,
properties: {},
geometry: {
type: geometryType,
coordinates: coordinate,
},
},
],
};
});
...
return (
<View>
<Geojson geojson={geojsonData}/>
</View>
After a suggestion in the answer section, i have changed my code to use useState hook.在答案部分提出建议后,我已将代码更改为使用 useState 挂钩。 However i am still getting an error for type: Type where it "is not assignable to parameter of type '(prevState: undefined) => undefined'."
但是,我仍然收到类型错误:类型“不可分配给'(prevState:undefined)=> undefined'类型的参数。” Updated Code:
更新代码:
const[geojsonData, setGeoData] = useState()
...
useEffect(() => {
if(componentVisible == true){
setGeoData({
type: Type,
features: [
{
type: featuresType,
properties: {},
geometry: {
type: geometryType,
coordinates: coordinate,
},
},
],
});
});
...
return (
<View>
<Geojson geojson={geojsonData}/>
</View>
You won't find it effective to change a let
variable like that inside a function component.您不会发现像在 function 组件中那样更改
let
变量是有效的。 Instead, you should use a useState
hook .相反,您应该使用
useState
挂钩。
const [geojsonData, setGeojsonData] = useState();
//...
useEffect(() => {
if(componentVisible == true){
setGeojsonData(
//include your data here
);
}
},[componentVisible]); //remember to include your dependencies
//...
return (
<View>
<Geojson geojson={geojsonData}/>
</View>
That being said, since you don't appear to actually be getting any new data in your useEffect
call, it might be more effective to just use a conditional render:话虽如此,由于您似乎实际上并没有在
useEffect
调用中获得任何新数据,因此仅使用条件渲染可能更有效:
let geojsonData = //your data
return (
<View>
{componentVisible ? <Geojson geojson={geojsonData}/> : null}
</View>
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.