State not changing after calling this.setState

前端 未结 3 489
余生分开走
余生分开走 2021-01-14 05:53

I am getting the data from my form component and trying to set the state of my app component with this data.

However, the state.data is an empty object and is not up

相关标签:
3条回答
  • 2021-01-14 06:40

    I just want to add, that if you will do like this its not going to work:

    this.setState({things} , console.log(this.state))
    

    You have to pass a refarence to the call back and not the exscutable code itself. If you won't do so, the function will envoke before the state is updated,even you will see the log.

    0 讨论(0)
  • 2021-01-14 06:43

    setState() is an async call in React. So you won't likely get the updated state value in the next line. To check the updated value on successful state update, you could check in the callback handler.

    Change this

    onSubmit = (model) => {
      console.log("Outer", model);
      this.setState({
        data: model
      });
      console.log("Form: ", this.state);
    }
    

    to

    onSubmit = (model) => {
      console.log("Outer", model);
      this.setState({
        data: model
      }, () => {
        console.log("Form: ", this.state);
      });
    }
    
    0 讨论(0)
  • 2021-01-14 06:44

    As per the react docs, setState is an asynchronous call. You can ensure your state has updated to perform a particular action in two ways as shown below:

    1. You can pass the setState a function which will have your current state and props and you the value you return will be your next state of the component. Keep in mind following:

    state is a reference to the component state at the time the change is being applied. It should not be directly mutated. Instead, changes should be represented by building a new object based on the input from state and props.

    Following is an example:

     this.setState((state, props) => {
          //do something
          return {counter: state.counter + props.step};
        });
    
    1. You can pass a callback to the setState function as mentioned in Dinesh's answer. The callback will be executed once the state has been updated successfully hence ensuring you will have the updated state in the call back.

    Following is an example:

    this.setState({ ...new state }, () => {
     // do something
    });
    

    Hope it helps.

    0 讨论(0)
提交回复
热议问题