Javascript 通过axios库方法设置状态后,Json数据未在ReactJS类中呈现?
我试图通过axios库函数axios.get()方法读取JSON数据。它工作正常,在控制台中记录正确的用户名,并正确设置用户变量的状态。但当我尝试在render method()中呈现相同的对象时,它停止工作。 链接到Javascript 通过axios库方法设置状态后,Json数据未在ReactJS类中呈现?,javascript,json,reactjs,axios,react-dom,Javascript,Json,Reactjs,Axios,React Dom,我试图通过axios库函数axios.get()方法读取JSON数据。它工作正常,在控制台中记录正确的用户名,并正确设置用户变量的状态。但当我尝试在render method()中呈现相同的对象时,它停止工作。 链接到 类TableData扩展了React.Component{ 建造师(道具){ 超级(道具); 此.state={ 用户:[], 计数:0 }; } componentDidMount(){ axios .得到(`https://fcctop100.herokuapp.com/a
类TableData扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
用户:[],
计数:0
};
}
componentDidMount(){
axios
.得到(`https://fcctop100.herokuapp.com/api/fccusers/top/recent`)
。然后(响应=>{
this.setState({users:response.data});
console.log(this.state.users[2].username);
});
}
render(){
返回(
你好{this.state.users[2].username}
);
}
}
render(,document.getElementById(“容器”)代码>
在一段时间内,this.state.users是一个空数组。因此,当渲染函数访问this.state.users[2].username时,this.state.users[2]可能未定义,从而引发异常。您只需更改渲染函数即可处理数组为空的情况
还要注意,this.setState
可以是异步的,因此调用setState后的log语句可能看不到新状态。如果要等到setState完成,可以将回调函数传递给this.setState
类TableData扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
用户:[],
计数:0
};
}
componentDidMount(){
axios
.得到(`https://fcctop100.herokuapp.com/api/fccusers/top/recent`)
。然后(响应=>{
this.setState({users:response.data},函数(){
console.log(this.state.users[2].username);
});
});
}
render(){
返回(
你好{this.state.users[2]&&this.state.users[2].username}
);
}
}
render(,document.getElementById(“容器”)代码>
render
方法正在尝试呈现此.state.users[2]。username
在组件装载时为未定义的
渲染方法应类似于此,以便仅当this.state.users数组包含2个或更多元素时才进行渲染
render() {
return this.state.users.length > 1 ? (
<div>Hello {this.state.users[2].username}</div>
) : null;
}
render(){
是否返回this.state.users.length>1(
你好{this.state.users[2].username}
):null;
}
而且,我不认为
console.log(this.state.users[2].username)
应该返回正确的数据,因为setState
是异步的。为了100%准确:setState
可能会延迟状态更新,但并不总是异步的。请参阅:@marzelin感谢您的澄清:)