每个人 我是React Native的新手,正在尝试一些可能会困扰我的事情。我希望使用fetch命令提取数据并将其保存为我的状态的属性。这是我的代码:
componentDidMount() {
fetch('http://swapi.co/api/people/')
.then(response => response.json())
.then(responseData => {
this.setState({
tweets: responseData.results
});
console.log(this.state.tweets)
})
.catch(error => {
alert('Fetching and parsing data error ' + error);
})
.then(console.log(this.state.tweets));
} 第一个console.log()输出我提取的正确数组,但是第二个console.log()显示null。
有人可以解释为什么会这样吗? 谢谢
答案 0 :(得分:0)
setState
是异步的,因此设置后立即检查状态将不起作用。
要查看设置后的状态-传递回调以将状态设置为第二个参数。
this.setState({
tweets: responseData.results
}, () => console.log(this.state.tweets));
setState
也调用render
方法,因此您可以在那里预览新状态。
答案 1 :(得分:0)
如果您将console.log标记为“ first”,“ second”等,您将看到最后一个console.log首先被调用。如此固定,您应该使用胖箭头或匿名函数包装最后一个console.log。因此,它将按您想要的顺序调用。
componentDidMount() {
fetch('http://swapi.co/api/people/')
.then(response => response.json())
.then(responseData => {
this.setState({
tweets: responseData.results
});
console.log(this.state.tweets)
})
.catch(error => {
alert('Fetching and parsing data error ' + error);
})
.then(()=>console.log(this.state.tweets)); // Here
}