如何在循环对象数组中推送值?

时间:2019-02-01 09:09:27

标签: javascript arrays reactjs object state

如何在循环中以反应状态将对象列表中的数组推送?

我的默认状态:

this.state = {
            users: [
                {
                    id:1,
                    name: 'John'
                },
                {
                    id:2,
                    name: 'Nick'
                }
            ]
        };

我尝试了类似的方法,但是它不起作用

changeHandler (currentUser, newValue) {
        const users = this.state.users;
        for (var i in users) {
            if (users[i].id == currentUser) {
                this.setState({
                    users: [...this.state.users[i], {newValue: newValue}]
                })
            }
            break;
        }
    }

所以我希望看到:

default state - {id:1,name: 'John'},{id:2, name: 'Nick'} 
use changeHandler(2,1) - {id:1,name: 'John'},{id:2, name: 'Nick', newValue: [1]}
use changeHandler(2,2) - {id:1,name: 'John'},{id:2, name: 'Nick', newValue: [1,2]}
use changeHandler(2,3) - {id:1,name: 'John'},{id:2, name: 'Nick', newValue: [1,2,3]}

3 个答案:

答案 0 :(得分:1)

您可以使用诸如

这样的扩展语法来映射和更新状态
changeHandler (currentUser, newValue) {
    const users = this.state.users;
    this.setState(prevState => ({
       users: prevState.users.map((user => {
           if (user.id == currentUser) {
              return {
                  ...user,
                  newValue: [...(user.newValue || []), newValue]
              }
           }
           return user
       }))
    }))
}

答案 1 :(得分:0)

您可以使用地图:

this.state.users.map(
  (user)=>user.id===currentUser
    //if user id is current user then copy user to new object {...user}
    //set newValue to user.newValue or empty array newValue:(user.newValue||[])
    //add the newValue to user.newValue: .concat(newValue)
    ? {...user,newValue:(user.newValue||[]).concat(newValue)
    //user is is not currentUser, just return the user as is
    : user
)

答案 2 :(得分:0)

短之一:

changeHandler (currentUserId, newValue) {
  this.setState(({ users }) => ({
    users: users.map(user => ({
      ...user,
      ...(
        user.id === currentUserId
          ? { newValue: [...(user.newValue || []), newValue]}
          : {}
      ),
    }))
  }));
}

长之一:

changeHandler (currentUserId, newValue) {
  this.setState(({ users }) => {
    const otherUsers = users.filter({ id } => id !== currentUserId);
    const currentUser = users.find({ id } => id === currentUserId);
    return {
      users: [
        ...otherUsers,
        {
          ...currentUser,
          newValue: [
            ...(currentUser.newValue || []),
            newValue
          ],
        },
      ],
    };
  });
}

长版的短版:

changeHandler (currentUserId, newValue) {
  this.setState(({ users }) => ({
    users: [
      ...users.filter({ id } => id !== currentUserId),
      {
        ...users.find({ id } => id === currentUserId),
        newValue: [...(currentUser.newValue || []), newValue],
      },
    ],
  }));
}