从反应状态

时间:2016-04-28 00:17:59

标签: reactjs state

我正在使用react(v0.14)视图的状态来保存未保存的用户ID和用户对象的键值对。例如:

onChange = (user, field) => {
  return (event) => {
    let newUser = _.clone(this.state[user.uuid] || user);
    _.assign(newUser, {[field]: event.target.value});
    this.setState({
      [user.uuid]: newUser
    });
  }
}

render() {
   let usersJsx = users.map((user, i) => {
     return <div key={i}>
       <input type="text" value={user.name}
         onChange={this.onChange(user, 'name')}/>
     </div>;
   });

   let numberUnsavedUsers = _.keys(this.state).length;

   // ... etc
}

这一切都完美无缺,直到我找到保存方法:

persistUsers = (event) => {

  let unsavedUsers = _.toArray(this.state);
  updateUsers(unsavedUsers, {
    onSuccessCb: (savedUsers) => {

      // Would prefer to remove these two lines and replace
      // with `this.setState({});` but this doesn't work... i.e.
      // the state is left untouched rather than being
      // replaced with `{}`.  This makes sense.  I guess I was hoping
      // someone might point me towards a this.replaceState()
      // alternative.
      this.setState({nothing: true}); // triggers a state change event.
      this.state = {};  // wipes out the state.
    }    
  });
}

我已经四处搜索,但只发现修改嵌套对象或数组的人而不是顶级键值。

1 个答案:

答案 0 :(得分:5)

您需要使用replaceState代替setState

更新: replaceState is being deprecated。您应该遵循建议并使用setState和空值。

推荐:

您应该命名数据并使用setState,以便您可以更轻松地使用它。

而不是:

//bad
this.setState({
  [user.uuid]: newUser
});

使用:

//good
this.setState({
 newUser: {uuid: user.uuid}
})

如果您的州位于{unsavedUsers: {userData}}而不是{userData},那么您可以轻松setState({unsavedUsers: {}})而不会引入replaceState

replaceState是一种反模式,因为它不常用。

原始答案:

  

setState()类似,但删除不在newState对象中的任何预先存在的状态键。

Documentation

this.replaceState({})将删除所有对象。