如何在reactJS中“更新”状态?

时间:2017-02-25 17:30:01

标签: javascript json reactjs react-jsx

我有这个

- Ajax Callback:

        success:function(data) {
            self.setState({
                user: {
                    id_user: data.session.id_user,
                    firstname_user: data.session.firstname_user,
                    lastname_user: data.session.lastname_user,
                    action: "updateUser"
                },
            });
        }

- 并且对我的输入进行处理:

handleChange(){
    this.setState({
        user: {
            firstname_user: this.firstname_user.refs.input.value,
            lastname_user: this.lastname_user.refs.input.value
        }
    });
}

给这个:

 console.log(this.state.user);

 /*
   user
      firstname_user: "Blablabla"
      lastname_user: "Blablabla"
 */

相反:      的console.log(this.state.user);

 /*
    user
      id_user: XX
      firstname_user: "Blablabla"
      lastname_user: "Blablabla"
      action: "updateUser"
 */

触发handleChange后,this.state.user会删除id_useraction密钥。因此this.state.user仅留下firstname_userlastname_user。为什么?

我没有删除任何键,所以我不明白为什么。

如何解决这个问题?

由于

1 个答案:

答案 0 :(得分:1)

setState(nextStateObject)执行nextStateObject到当前状态的浅层合并,因此嵌套对象(例如您的state.user)不会被扩展但会被覆盖。您可以使用Object.assign来解决问题:

handleChange(){
    let updatedUser = Object.assign({}, this.state.user, {
            firstname_user: this.firstname_user.refs.input.value,
            lastname_user: this.lastname_user.refs.input.value
        });
    this.setState({
        user: updatedUser
    });
}

请检查setState方法的实际docs