我是 redux 和 react 的新手,我正在尝试更新 REDUX 存储中的嵌套状态,但无法对其进行整理
2020-08-15
53
我遗漏了什么?请帮忙解决 _/_ 我无法正确更新 redux 存储状态而不中断
这是我在发布数据之前 redux 存储状态中的当前状态
next state Object {
"highlights": Object {
"errMess": null,
"highlights": Array [],
"isLoading": true,
},
"posts": Object {
"errMess": null,
"isLoading": false,
"posts": Array [
Object {
"__v": 0,
"_id": "5f37c3ebc8cb6a46c89bc33c",
"by": Object {
"_id": "5ed8d7fcfd3da42bc426992a",
"name": "mad",
"username": "mad",
},
"content": "this is first post",
"contentWarn": false,
"createdAt": "2020-08-15T11:15:55.986Z",
"flaged": false,
"heading": "first pot",
"report": 0,
"updatedAt": "2020-08-15T11:15:55.986Z",
},
],
},
}
然后使用 Reducer 执行添加新帖子操作====>
export const posts = (
state = { isLoading: true, errMess: null, posts: [] },
action
) => {
switch (action.type) {
case ActionTypes.UPDATE_POSTS:
return {
posts: state.posts.posts.concat(action.payload),
};
default:
return state;
}
};
这是返回的错误
action Object {
"payload": [TypeError: undefined is not an object (evaluating 'state.posts.posts.concat')],
"type": "UPDATE_POSTS_FAILED",
}
undefined is not an object (evaluating 'state.posts.posts.concat')
* Redux\posts.js:24:13 in posts
这是我想要发生的结果
next state Object {
"highlights": Object {
"errMess": null,
"highlights": Array [],
"isLoading": true,
},
"posts": Object {
"errMess": null,
"isLoading": false,
"posts": Array [
Object {
"__v": 0,
"_id": "5f37c3ebc8cb6a46c89bc33c",
"by": Object {
"_id": "5ed8d7fcfd3da42bc426992a",
"name": "mad",
"username": "mad",
},
"content": "this is first post",
"contentWarn": false,
"createdAt": "2020-08-15T11:15:55.986Z",
"flaged": false,
"heading": "first pot",
"report": 0,
"updatedAt": "2020-08-15T11:15:55.986Z",
},
Object {
"__v": 0,
"_id": "5f37c3ebc8cb6a46c89bc33c",
"by": Object {
"_id": "5ed8d7fcfd3da42bc426992a",
"name": "mad",
"username": "mad",
},
"content": "this is second post",
"contentWarn": false,
"createdAt": "2020-08-15T11:15:55.986Z",
"flaged": false,
"heading": "second post",
"report": 0,
"updatedAt": "2020-08-15T11:15:55.986Z",
}
],
},
}
2个回答
你的 Reducer 应该有这样的结构,并且有两级帖子:
export const posts = (
state = {
highlights: {
errMess: null,
highlights: [],
isLoading: true,
},
posts: { isLoading: true, errMess: null, posts: [] },
},
action
) => {
switch (action.type) {
case ActionTypes.UPDATE_POSTS:
return {
...state,
posts: state.posts.posts.concat(action.payload),
};
default:
return state;
}
};
并且尽量在状态下保持相同的数据结构,比如高亮!
Lafi
2020-08-15
return {
...state,
posts: state.posts.concat(action.payload),
}
此 Reducer 有效 注意:我在单独的文件中使用高亮 Reducer
Madhav Gautam
2020-08-16