Next.js 状态更改不重新渲染 UI

Next.js state change not re-rendering UI

我正在尝试使用 Next.js 在 React 中有条件地呈现元素。但是,我的组件 UI 没有在状态更改时更新。

我已验证调用 this.setState 后状态正在改变,但 UI 保持不变。

预计 UI 在单击 h5 "meeee" 后显示 "naaaah"。 在setState改后回调中可以看到this.state.test为false。

class Sidebar extends React.Component {
  constructor() {
    super();
    this.state = {
      test: true,
      sections: [
        {
          title: "Getting Started",
          collapsed: false,
          subsections: ["intro", "about", "zeppy"]
        }
      ]
    };
    this.toggleTrue.bind(this);
  }

  toggleTrue() {
    this.setState(
      state => {
        state.test = false;
      },
      state => {
        console.log("done", this.state);
      }
    );
  }

render() {
    return (
<div>
        {this.state.test ? (
          <h5 onClick={() => this.toggleTrue()}>meeee</h5>
        ) : (
          <h5>nahhh</h5>
        )}
</div>)
}

您的 setState() 更新程序应该 return 更新状态,而不是直接编辑状态:

  toggleTrue() {
    this.setState(
      state => { return {
        test: false;
      }},
      state => {
        console.log("done", this.state);
      }
    );
  }

为了表明它是 return 状态对象,我说得有点冗长。您不需要 return 一个完整的状态对象,只需要更新您想要更新的字段

实际上你把事情复杂化了,你应该这样做,

this.setState({test: false}, ()=> console.log("done", this.state));

Demo

注意:更新嵌套状态时应使用previous state

使用以前的状态你可以做到这一点,

this.setState(state => ({
    ...state,
    test: false
}), ()=> console.log("done", this.state))