在 React Redux reducer 中更新数组对象 [英] Update array object in React Redux reducer

查看:49
本文介绍了在 React Redux reducer 中更新数组对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该很简单,但我没有找到我想要的简单答案.我有一个减速器:

This should be simple but I'm not finding the simple answer I want. I have a reducer:

const posts = (state = null, action) => {
  switch(action.type){
    case "PUBLISH_POST":
        return state;
    case "UNPUBLISH_POST":
        return state;
    default:
        return postList;
  }
}

我有一个带有 IDstatus 的帖子列表.我正在发送我的帖子 ID,但无法找出简单地将已单击项目的 status 从 0 更新为 1 的逻辑.我找到了很多半解决方案,但它们看起来都很冗长和丑陋 - 在这种情况下实现它的最短/最佳方法是什么?

I have a list of posts with ID's and a status. I'm sending in my post ID but can't figure out the logic to simply update the status from 0 to 1 for the item which has been clicked. I've found plenty of half-solutions but they all seem verbose and ugly - what's the shortest/best way of achieving it in this case?

示例数据:

{
    id:1,
    user:"Bob Smith",
    content:"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vulputate mauris vitae diam euismod convallis. Donec dui est, suscipit at dui vitae, sagittis efficitur turpis. ",
    status:1 
}

推荐答案

假设您的 action 类似于:

{
  type: 'UNPUBLISH_POST',
  payload: {
    id: 1,
    user: 'Bob Smith',
    content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vulputate mauris vitae diam euismod convallis. Donec dui est, suscipit at dui vitae, sagittis efficitur turpis. ',
    status: 1
  }
}

只需使用传播运算符即可:

const posts = (state = null, action) => {
  switch(action.type){
    case "PUBLISH_POST":
    case "UNPUBLISH_POST":
        const index = this.state.findIndex(post => post.id === action.payload.id)

        return [
           ...state.slice(0, index), // everything before current post
           {
              ...state[index],
              status: action.type === 'PUBLISH_POST' ? 1 : 0,
           },
           ...state.slice(index + 1), // everything after current post
        ]
    default:
        return postList;
  }
}

这篇关于在 React Redux reducer 中更新数组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆