简体   繁体   中英

computed style in setState of react doesn't work

I have nested form objects but I try to setState using one handler, somehow doesn't work

  constructor() {
    super()

    this.state = {
      form: {
        name: '',
        location: ''
      }
    }
  }

  handleFormInput = (event) => {

    this.setState({
      [this.state.form[event.target.name]]: event.target.value
    })

    setTimeout(() => {
      console.log(this.state.form)
    },50)

  }

event.target.name can be name and location.

I think this code is not working properly:

this.setState({ [this.state.form[event.target.name]]: event.target.value })

alternative is :

handleFormInput = (event) => {
    //New code
    let obj = {}
    obj[this.state.form[event.target.name]] = event.target.value

    this.setState(obj,() => { console.log(this.state.form) })
  }

to view updated state , use callback function param of this.setState

You cannot directly access and modify a dynamic state within the setState function, you would rather get a copy of the state object and modify it. Also as you may already know that setState is async and hence you have a setTimeout function which is not necessary since setState provides you a callback function which is executed when state has changed.

handleFormInput = (event) => {
    var form = {...this.state.form}
    form[event.target.name] = event.target.value;
    this.setState({
      form
    }, () => {this.state.form})

  }

setState is asynchronous, your state will properly update somehow after the call. Then render will be called again. Try checking your new state in render or in componentWillUpdate : https://facebook.github.io/react/docs/react-component.html#componentwillupdate

You should never look for a change in your state right after changing your state

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM