React setState 不会立即更新状态

时间:2021-06-17 09:08:18

标签: reactjs

我必须选择下拉菜单两次才能更新详细信息。

     <Dropdown
        onSelect={(e) => {
          if (e === "YES") {
            this.setState({
              BasePlantsSiteHire: "",
            });
          } else if (e === "NO") {
            this.setState({
              BasePlantsSiteHire: "N",
            });
          } else if (e === "ONLY") {
            this.setState({
              BasePlantsSiteHire: "Y",
            });
          }
          this.componentDidMount();
          console.log(
            "Status Updated: ",
            this.state.BasePlantsSiteHire
          );
        }}
      >
        <Dropdown.Toggle style={{ background: "none", border: "none" }}>
          <CIcon name="cil-settings" />
        </Dropdown.Toggle>
        <Dropdown.Menu className="pt-0" placement="bottom-end">
          <Dropdown.Item
            eventKey="YES"
            name="YES"
            key="YES"
            value="YES"
          >
            SubHire Include
          </Dropdown.Item>
          <Dropdown.Item eventKey="NO" name="NO" key="NO" value="NO">
            SubHire Exclude
          </Dropdown.Item>
          <Dropdown.Item
            eventKey="ONLY"
            name="ONLY"
            key="ONLY"
            value="ONLY"
          >
            SubHire Only
          </Dropdown.Item>
        </Dropdown.Menu>
      </Dropdown>

我的问题是,当我调用 select 下拉列表时,它不会立即更新,需要选择两次才能获取操作和 console.log 状态。

enter image description here

2 个答案:

答案 0 :(得分:3)

React 的 setState 函数是异步的。你所经历的是完全正常的行为。如果您需要在状态更新后执行某些操作,您可以将回调函数作为第二个参数传递给 setState,如下所示:

    this.setState({
                ...
            }, () => { 
                  console.log(
                    "Status Updated: ",
                    this.state.BasePlantsSiteHire
                  );
                  // do something here
     })

另外,请不要显式调用 componentDidMount,这些是组件生命周期方法,在组件的整个生命周期中都会被 React 自身调用!

答案 1 :(得分:1)

发生这种情况是因为 setState 是一个异步函数。 你应该回电:

 this.setState(prevValue => {
   // someLogic
   return newState.
})

您可以在那里找到更多信息: