javascript - 我是 redux 的新手并做出反应我正在尝试更新 REDUX 存储中的嵌套状态,但无法对其进行排序
问题描述
我在哪里失踪?请帮助解决这个问题_/_我无法正确更新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执行添加新的post操作====>
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",
}
],
},
}
解决方案
你的 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;
}
};
并尝试在状态中保持相同的数据结构,例如亮点!
推荐阅读
- gradle - Gatling 报告场景中第一个请求组的响应时间更长
- sql-server - 创建 2 对唯一 id 数据行
- javascript - 在 jquery 中调整视口大小时禁用和启用滚动窗口
- java - 如何正确地只允许业务部分分类帐中的数量为 5
- java - Libgdx 断言失败 [表达式:pointCount > 0]
- javascript - 如何从另一个页面获取值并将其输出到选择列表?JAVASCRIPT
- mysql - 更换电脑后我的数据库变成了“只读”
- c++ - 在 C++ 中重载 -> 运算符以返回自定义对象
- javascript - 如何使用 Leaflet Marker onclick 路由到 Ionic 4 中的另一个页面
- php - 数据表列内的 MySQL 循环