Arrays 无法读取属性';目的地';当react state为数组时,为未定义
当我的react状态是一个对象时,我可以在render方法中获得它的属性, 但当我将状态设置为array并在render方法中使用state[0].属性时,它会给我一个未定义的错误,无法理解,有什么帮助吗???谢谢Arrays 无法读取属性';目的地';当react state为数组时,为未定义,arrays,reactjs,state,Arrays,Reactjs,State,当我的react状态是一个对象时,我可以在render方法中获得它的属性, 但当我将状态设置为array并在render方法中使用state[0].属性时,它会给我一个未定义的错误,无法理解,有什么帮助吗???谢谢 class App extends Component { state={ dataArray:[] } componentDidMount(){ this.getTrainInfo(); } getTrainInfo=()=>{ fetch
class App extends Component {
state={
dataArray:[]
}
componentDidMount(){
this.getTrainInfo();
}
getTrainInfo=()=>{
fetch('https://api-v3.mbta.com/routes')
.then(response=>response.json())
.then(res=>{
//res will return an array of objects
let arr=[];
let data={};
data.destination=res.data[0].attributes.direction_destinations[0];
data.lineID=res.data[0].relationships.line.data.id
arr.push(data);
this.setState({dataArray:arr});
//I put a console.log(dataArray) here, I can get
// [{destination:xxx, lineID:xxx }] back.
})
}
render() {
//in here, I also can get the array: [{destination: xxx, lineID: xxx}]
let data=this.state.dataArray;
//but in here, I get error saying property destination is undefined,
//why?
let destination=data[0].destination;
//console.log(destination);
return (
<div className="App">
<h1>Train info</h1>
</div>
);
}
}
类应用程序扩展组件{
陈述={
数据数组:[]
}
componentDidMount(){
this.getTrainInfo();
}
getTrainInfo=()=>{
取('https://api-v3.mbta.com/routes')
.then(response=>response.json())
.然后(res=>{
//res将返回一个对象数组
设arr=[];
让数据={};
data.destination=res.data[0]。attributes.direction_destinations[0];
data.lineID=res.data[0]。relationships.line.data.id
arr.push(数据);
this.setState({dataArray:arr});
//我在这里放了一个console.log(dataArray),我可以
//[{destination:xxx,lineID:xxx}]返回。
})
}
render(){
//在这里,我还可以得到数组:[{destination:xxx,lineID:xxx}]
让data=this.state.dataArray;
//但在这里,我得到一个错误,说属性目的地未定义,
//为什么??
让目的地=数据[0]。目的地;
//console.log(目的地);
返回(
列车信息
);
}
}
这是正常行为。React将在执行componentDidMount()
中的逻辑之前呈现组件一次,这就是为什么会出现未定义的错误,因为初始状态以空数组开始
要解决这个问题,通常的做法是在组件使用新数据更新时具有“加载状态”。因此,当状态最终更新时,组件将重新渲染并显示所需的内容
在渲染中,尝试执行以下操作:
render() {
let data=this.state.dataArray;
if(this.state.dataArray.length == 0){
return Loading...
} else {
return (
<div className="App">
// whatever logic you want to display
<h1>Train info</h1>
</div>
)
}
render(){
让data=this.state.dataArray;
if(this.state.dataArray.length==0){
返回加载。。。
}否则{
返回(
//不管你想显示什么逻辑
列车信息
)
}
您需要添加条件,因为在初始渲染时,dataArray是空数组,并且其中没有任何对象
从第二次渲染开始,数据数组中有数据,所以添加以下条件
if(this.state.dataArray.length){ //this condition will be true when dataArray length is greater than zero
let destination=data[0].destination;
console.log(destination); //this will print the value
}
@Young Lee不客气。如果答案有助于您解决问题,请进行投票并接受答案。问题是,您需要在初始时间检查数组是否有任何值,并且在您提供的代码中没有。因为在首次渲染后调用componentDidMount,您的数组为空,并且存在该错误。流程继续这样做:渲染>组件安装>重新渲染(在获得一些值后)