首页 > 解决方案 > 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 函数中无法理解的部分,当我控制台记录状态时,我希望更新状态显示在这里,但它没有我什至正在按顺序执行这些功能。

提前致谢。

标签: reactjs

解决方案


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()
} )

推荐阅读