我开始一个项目,做出反应,以提高我的技能。但是在我的项目中,当我尝试在钩子ComponentDidMount()中设置从json文件构建的数组时出现错误,我认为这个错误是由于前一个错误导致的:
cannot read property 0 of undefined
我是否需要特定的库来正确解析json文件?
发生最后一次错误:
Can't call setState (or forceUpdate) on an unmounted component.
具有该方法的组件在这里:
class SimpleMap extends Component{
state={
positions:[],
isLoading:true
}
componentDidMount(){
console.log(data.latlngs);
this.switchCoord(data.latlngs);
}
switchCoord(datas){
//console.log( datas);
console.log("-----------------");
//remplacer latlngs par data pour fonctionner avec le fichier json
datas.forEach(data =>{
let newLat;
let newLng;
let tableWithNewCoord =[];
//console.log(data)
data.forEach(d => {
newLat = d[1];
newLng = d[0];
let switchCoordData =[newLat,newLng];
tableWithNewCoord.push(switchCoordData);
})
this.setState({
positions:[...this.state.positions,tableWithNewCoord]
})
})
}
json文件是从文件夹资产导入的,它具有以下形式:
{
"latlngs":
[[2.367272,48.662474],[2.36523,48.663373],
[2.360465,48.66607],[2.3557,48.667419],
[2.352978,48.667868],[2.348893,48.669217],
[2.34549,48.671015],[2.342767,48.672813]...]
}
在此先感谢您的帮助。最好的祝福
我相信问题在于你的switchCoord
功能。你可以试试你的这个重构功能:
switchCoord(data) //actually data should be renamed to latlngs for readability
{
let tableWithNewCoord = [];
data.forEach( (coord) => {
tableWithNewCoord.push([coord[1], coord[0]])
});
this.setState({positions: tableWithNewCoord});
}