我正在使用 react (v0.14) View 的状态来保存未保存的用户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
}

在我进入save方法之前,这一切都可以正常工作:
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.
    }
  });
}

我四处搜寻,但只发现有人在修改嵌套对象或数组,而不是顶级键值。

最佳答案

您需要使用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是一种反模式,因为它很少使用。

原始答案:



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

关于reactjs - 从 react 状态删除 key 的正确方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36903114/

10-13 02:23