reactjs - setState 没有在我的其他方法中更新
问题描述
我对反应很陌生,我很困惑为什么我的状态没有用我的另一种方法更新,请参见下面的示例。
fetchMovies = () => {
const self = this;
axios.get("https://api.themoviedb.org/3/trending/movie/day?api_key=XXXXXXX")
.then(function(response){
console.log(response.data)
self.setState({
collection: response.data.results
})
console.log(self.state.collection)
});
}
makeRow = () => {
console.log(this.state.collection.length);
if(this.state.collection.length !== 0) {
var movieRows = [];
this.state.collection.forEach(function (i) {
movieRows.push(<p>{i.id}</p>);
});
this.setState({
movieRow: movieRows
})
}
}
componentDidMount() {
this.fetchMovies();
this.makeRow();
}
当在 fetchMovies 函数内部时,我可以访问集合并且它具有所有数据,但这是我在 makeRow 函数中无法理解的部分,当我控制台记录状态时,我希望更新状态显示在这里,但它没有我什至正在按顺序执行这些功能。
提前致谢。
解决方案
该setState()
文档包含以下段落:
将
setState()
其视为更新组件的请求而不是立即命令。为了更好地感知性能,React 可能会延迟它,然后一次更新多个组件。React 不保证立即应用状态更改。
要访问修改后的状态,您需要使用函数签名setState(updater, [callback])
,所以在您的情况下应该是;
self.setState({
collection: response.data.results
}, () => { // Will be executed after state update
console.log(self.state.collection)
// Call your make row function here and remove it from componentDidMount if that is all it does.
self.makeRow()
} )
推荐阅读
- node.js - Mongoose NodeJS Express - 如何将数据推送到特定的子文档对象数组
- javascript - 为什么 setTimout 在渲染反应组件时在浏览器中显示一个随机整数,以及如何解决这个问题?
- python - 这个神经网络实现的错误在哪里?
- dns - 将子域指向 Vercel 上的 Next.js 页面
- django - django-tables2:显示字典
- r - 在ggplot中缩放两个y轴
- cuda - Cuda中的静态关键字
- react-native - 如何使用本机反应悬停在文本下划线?
- android - Android searchview在搜索后隐藏在recyclerview中
- vue.js - 我如何在 vue 中做一个等效的 JS?(n 个数的增量)