Reactjs:立即更新状态

Reactjs:立即更新状态,reactjs,Reactjs,这里是新手。我知道setState()是异步的。我知道如果我执行setState(),那么状态将排队并成批处理,因此我不会立即看到状态更改。很公平 我还阅读了SO中的以下链接和其他问题: 我可以使用:setState中的回调方法、componentDidUpdate()生命周期方法、concat(如果状态是数组)等等。我可以使用所有这些方法。我的问题很简单,而且在过去的两天里,我一直在为这个问题绞尽脑汁,所以我现在简直是束手无策 我有这样的逻辑: class ItemList extends

这里是新手。我知道setState()是异步的。我知道如果我执行setState(),那么状态将排队并成批处理,因此我不会立即看到状态更改。很公平

我还阅读了SO中的以下链接和其他问题:

我可以使用:setState中的回调方法、componentDidUpdate()生命周期方法、concat(如果状态是数组)等等。我可以使用所有这些方法。我的问题很简单,而且在过去的两天里,我一直在为这个问题绞尽脑汁,所以我现在简直是束手无策

我有这样的逻辑:

class ItemList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {showCompleted: false};
        this.shouldShowFullList = false;
        this.onShowCompleted = this.onShowCompleted.bind(this);
    }

    onShowCompleted(event) {
        this.setState({showCompleted: event}, () => {this.shouldShowFullList = this.state.showCompleted;});
    }

    render() {
        if (this.shouldShowFullList) {
            return this.renderAllItemsIncludingCompleted();
        } else {
            return this.renderOnlyNotCompletedItems();
        }
    }

    ...
逻辑是不言自明的。我的问题是,即使在setState()的回调方法中调用this.shouldShowFullList,它仍然不会显示更新的值。this.shouldShowFullList的值应为true时为false,反之亦然。使this.shouldShowFullList的值和this.state.showCompleted保持同步的最佳方法是什么


注意:onShowCompleted()是从子组件触发的回调方法。选中名为“显示已完成”的复选框时,我应该显示项目的完整列表,或者只显示未完成的项目-类似于待办事项列表。

At
onShowCompleted
do

this.setState({ showCompleted: true })
或者如果要切换该值

this.setState({ showCompleted: !this.state.showCompleted })
然后在render方法中可以执行以下操作:

 if (this.state.showCompleted) {
   return this.renderAllItemsIncludingCompleted();
 } else {
   return this.renderOnlyNotCompletedItems();
 }
使用
setState
设置状态时,将使用
this.state
updated调用方法
render
。我认为
this.setState
的回调(第二个参数)是在渲染之后调用的

因为更新this.state会生成一个新的渲染,所以react似乎促使您在渲染方法中使用this.state。事实上,它是为这种用途而设计的。如果要生成在渲染中没有用途的变量,可以使用
this.myVariable
。最好的做法是在渲染(或依赖它的函数)中仅使用
this.state
this.props