Как поместить значение в массив объектов в цикле? - PullRequest
0 голосов
/ 01 февраля 2019

Как я могу вставить массив в список объектов в состоянии реакции в цикле?

Мое состояние по умолчанию:

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 голосов
/ 01 февраля 2019

Вы можете отобразить и обновить состояние, используя синтаксис распространения, например

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
       }))
    }))
}
0 голосов
/ 01 февраля 2019

Короткая:

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],
      },
    ],
  }));
}
0 голосов
/ 01 февраля 2019

Вы можете использовать карту:

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
)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...