在React Redux Reducer中更新数组对象

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

const posts = (state = null, action) => {

switch(action.type){

case "PUBLISH_POST":

return state;

case "UNPUBLISH_POST":

return state;

default:

return postList;

}

}

我有一个带有ID和的帖子列表status。我正在发送帖子ID,但无法弄清楚将status单击的项目从0 更新为1

的逻辑。我已经找到了很多半解决方案,但是它们似乎都很冗长和丑陋-在这种情况下,实现它的最短/最佳方法是什么?

示例数据:

{

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中更新数组对象 的全部内容, 来源链接: utcz.com/qa/421678.html

回到顶部