setState doesn't update the state immediately

前端 未结 12 2519
暖寄归人
暖寄归人 2020-11-21 05:25

I would like to ask why my state is not changing when I do an onclick event. I\'ve search a while ago that I need to bind the onclick function in constructor but still the s

12条回答
  •  暖寄归人
    2020-11-21 05:52

    According to React Docs

    React does not guarantee that the state changes are applied immediately. This makes reading this.state right after calling setState() a potential pitfall and can potentially return the existing value due to async nature . Instead, use componentDidUpdate or a setState callback that is executed right after setState operation is successful.Generally we recommend using componentDidUpdate() for such logic instead.

    Example:

    import React from "react";
    import ReactDOM from "react-dom";
    
    import "./styles.css";
    
    class App extends React.Component {
      constructor() {
        super();
        this.state = {
          counter: 1
        };
      }
      componentDidUpdate() {
        console.log("componentDidUpdate fired");
        console.log("STATE", this.state);
      }
    
      updateState = () => {
        this.setState(
          (state, props) => {
            return { counter: state.counter + 1 };
          });
      };
      render() {
        return (
          

    Hello CodeSandbox

    Start editing to see some magic happen!

    ); } } const rootElement = document.getElementById("root"); ReactDOM.render(, rootElement);

提交回复
热议问题