gpt4 book ai didi

javascript - ReduxReducer - 根据 id 过滤数组,然后更改键/值对

转载 作者:行者123 更新时间:2023-11-28 04:15:42 26 4
gpt4 key购买 nike

我有一组评论,我想根据 ID 进行过滤并更改特定的键/值对。我的控制台日志函数返回数组中的正确项目,但我不确定获取 .filter 函数结果并将“liked”键从“false”更改为“true”的正确语法。如果扩展运算符适合这种情况,我可以使用它。

import * as types from '../actions/actionTypes';
import initialState from './initialState';

export default function commentReducer(state = initialState.comments, action) {
switch (action.type) {
case types.ADD_COMMENT_LIKE_SUCCESS:
const content = Object.assign({}, state);
const likedComment = content.data.filter(comment => (
comment.id === action.commentId
));
console.log(likedComment[0]);
break;

default:
return state;
}
}

评论对象如下所示:

"data":{  
"data":[
{ id: '', comment: '', liked: false },
{ id: '', comment: '', liked: false },
{ id: '', comment: '', liked: false },
{ id: '', comment: '', liked: false }
],
"cursor":"CkUKEQoEZGF0ZRIJCNrwhcWhvdUCEixqFGRldn5kZXZlbG9wbWVudC0xMzAwchQLEgdDb21tZW50GICAgLSe_-cKDBgAIAE=",
"more":false,
"count":4
},

最佳答案

您正在使用具有正确语法的过滤器函数,尽管您的reducer应该返回具有该特定评论且喜欢的键值对为true的所有评论,这就是您可以继续使用 map 功能相同

import * as types from '../actions/actionTypes';
import initialState from './initialState';

export default function commentReducer(state = initialState.comments, action) {
switch (action.type) {
case types.ADD_COMMENT_LIKE_SUCCESS:
const content = Object.assign({}, state);
content.data = content.data.map(comment => {
const newObj = {...comment};
if(newObj.id === action.commentId)
{
newObj.likeKey = true;
}
return newObj;
});
console.log(content);
return content;
default:
return state;
}
}

Map 函数将返回您到目前为止拥有的所有评论,并更改特定的评论对象。希望这会有所帮助。

关于javascript - ReduxReducer - 根据 id 过滤数组,然后更改键/值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45878654/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com