反应的setState中的计算样式不起作用

时间:2017-08-07 07:57:07

标签: javascript reactjs ecmascript-6

我有嵌套的表单对象但我尝试使用一个处理程序setState,不知何故不起作用

  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可以是姓名和位置。

3 个答案:

答案 0 :(得分:1)

我认为此代码无法正常运行:

  

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

替代方案是:

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

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

要查看更新的state,请使用this.setState

的回调函数参数

答案 1 :(得分:1)

您无法直接访问和修改setState函数中的动态状态,您更愿意获取状态对象的副本并对其进行修改。另外您可能已经知道setStateasync,因此您有一个setTimeout函数,这是不必要的,因为setState为您提供了callback函数,在州改变时执行。

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

  }

答案 2 :(得分:0)

setState是异步的,您的状态将在调用后以某种方式正确更新。然后再次调用render。尝试在渲染或componentWillUpdate中检查新状态:https://facebook.github.io/react/docs/react-component.html#componentwillupdate

改变你的状态后,你永远不应该在你的州里寻找改变