khanam
khanam

Reputation: 99

The state does not change in react

Hi everyone I just learned react and have the following problem: When I change hideFormAdd in App.js, the statusForm in FormAdd.js only gets the first unmodified default value.

//file App.js
<TaskForm open={this.state.hideFormAdd}></TaskForm>
//file FormAdd.js
constructor(props) {
      super(props);
      this.state = {
        statusForm: this.props.open
      }
    }

Upvotes: 0

Views: 60

Answers (3)

Borni.Mr
Borni.Mr

Reputation: 679

in your app component, you must do a function to change the state.

state = {
  hideFormAdd: true,
}
handleHideForm(){
  this.setState({hideFormAdd: !this.state.HideFormAdd})
}

in your render function:

<button onClick={()=> this.handleHideForm()}> hide/show </button>
<TaskForm open={this.state.hideFormAdd}></TaskForm>

now in your TaskForm component you don't need to use the state , you can use this.props.open without to make her value in state

Upvotes: 0

Oshini
Oshini

Reputation: 633

As FMCorz Said you can do that inside componentDidUpdate(). and also you can do within render() as well

    render() {
        var statusForm= this.props.open;

     }

Upvotes: 1

FMCorz
FMCorz

Reputation: 2706

That is because the constructor is not called on subsequent renders, it is only called once to initialise the component. To update your state when the properties change, you must implement componentDidUpdate.

componentDidUpdate(prevProps) {
  if (this.props.open !== prevProps.open) {
    this.setState({statusForm: this.props.open});
  }
}

Note that in this example, you may not need to use the state at all, you could perhaps just refer to this.props.open in your component, thus eliminating the complexity of managing prop updates.

Upvotes: 5

Related Questions