Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 通过axios库方法设置状态后,Json数据未在ReactJS类中呈现?_Javascript_Json_Reactjs_Axios_React Dom - Fatal编程技术网

Javascript 通过axios库方法设置状态后,Json数据未在ReactJS类中呈现?

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

我试图通过axios库函数axios.get()方法读取JSON数据。它工作正常,在控制台中记录正确的用户名,并正确设置用户变量的状态。但当我尝试在render method()中呈现相同的对象时,它停止工作。 链接到

类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感谢您的澄清:)