axrising
@axrising

Как увеличивать число на 1 в redux?

Как увеличивать предыдущее число на 1 в redux после получение action?
Нужно при диспатче увеличивать id на 1 в массиве постов
P.S в action нету id, только postMessage и file

let initialState = {
  posts: [
    {
      id: 1,
      postMessage: 'Hello world',
      file: '',
    },
  ] as Array<PostType>,
}


case 'SN/PROFILE/ADD_POST': {
      let newPost = {
        id: 1,
        postMessage: action.post.postMessage,
        file: action.post.file,
      }
      return {
        ...state,
        posts: [...state.posts, newPost],
      }
    }
  • Вопрос задан
  • 85 просмотров
Решения вопроса 2
Seasle
@Seasle Куратор тега JavaScript
case 'SN/PROFILE/ADD_POST': {
  let newPost = {
    id: 1,
    postMessage: action.post.postMessage,
    file: action.post.file,
  }
+ let previousPost = state.posts[state.posts.length - 1] || null;
+ if (previousPost !== null) {
+   newPost.id = previousPost.id + 1;
+ }
  return {
    ...state,
    posts: [...state.posts, newPost],
  }
}
Ответ написан
Комментировать
web_Developer_Victor
@web_Developer_Victor
Что такое google?
case 'SN/PROFILE/ADD_POST': {
      let newPost = {
        id: state.posts.length, // or state.posts[state.posts.length - 1].id + 1;
        postMessage: action.post.postMessage,
        file: action.post.file,
      }
      return {
        ...state,
        posts: [...state.posts, newPost],
      }
    }
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы