How to update object in React state

时间:2016-04-15 14:58:59

标签: javascript reactjs coffeescript

I have an indexed list of users in the JS object (not array). It's part of the React state.

{
    1: { id: 1, name: "John" }
    2: { id: 2, name: "Jim" }
    3: { id: 3, name: "James" }
}

What's the best practice to:

  1. add a new user { id: 4, name: "Jane" } with id (4) as key
  2. remove a user with id 2
  3. change the name of user #2 to "Peter"

Without any immutable helpers. I'm using Coffeescript and Underscore (so _.extend is ok...).

Thanks.

5 个答案:

答案 0 :(得分:9)

This is what i would do

  • add: var newUsers = _.extend({}, users, { 4: { id: 4, ... } })
  • remove: var newUsers = _.extend({}, users) then delete newUsers['2']
  • change: var newUsers = _.extend({}, users) then newUsers['2'].name = 'Peter'

答案 1 :(得分:5)

If you're not using Flux, you use this.setState() to update the state object.

delUser(id) {
    const users = this.state.users;
    delete users[id];
    this.setState(users);
}

addChangeUser(id, name) {
    const users = this.state.users;
    users[id] = {id: id, name: name};
    this.setState(users);
}

Then you can execute your test cases with this:

addChangeUser(4, 'Jane);
addChangeUser(2, 'Peter');
delUser(2);

答案 2 :(得分:2)

除_.extend外,您可以使用Map存储user

let user = new Map();
user.set(4, { id: 4, name: "Jane" }); //adds with id (4) as key
user.myMap.set(2, { id: 2, name: "Peter" }); // set user #2 to "Peter"
user.delete(3); //deletes user with id 3

答案 3 :(得分:0)

setState也接受一个函数,您可能会发现它更直观

function add( user ) {
  this.setState( users => {
    users[ user.id ] = user
    return users
  }
}

function remove( id ) {
  this.setState( users => {
    delete users[ id ]
    return users
}

这些函数假设您的state对象 是您的users对象,如果它实际上是state.users那么您必须选择users } out,将函数传递给setState将始终通过实际的state对象进行调用。

在此示例中,add也可用于修改,具体取决于您的实际用例,您可能需要创建单独的帮助程序。

答案 4 :(得分:0)

使用点差:

添加

this.setState({
  ...this.state,
  4: { id: 4, name: "Jane" },
}

删除ID 2

let prevState = this.state;
let {"2": id, ...nextState} = prevState;
this.setState({
  ...nextState,
}

更改ID 2

this.setState({
  ...this.state,
  2: {
    ...this.state["2"],
    name: "Peter",
  }
}