Javascript 使用normalizer.js基于给定模式对redux状态进行非规范化
在过去的几周里,我一直在努力学习React和Redux。现在我遇到了一个我没有找到正确答案的问题 鉴于我有一些数据需要标准化: /posts.jsJavascript 使用normalizer.js基于给定模式对redux状态进行非规范化,javascript,php,reactjs,web,react-redux,Javascript,Php,Reactjs,Web,React Redux,在过去的几周里,我一直在努力学习React和Redux。现在我遇到了一个我没有找到正确答案的问题 鉴于我有一些数据需要标准化: /posts.js export function getPosts(state, action) { const { payload } = action; const { data, path } = payload; const comments = new schema.Entity("comments", {}, { idAtt
export function getPosts(state, action) {
const { payload } = action;
const { data, path } = payload;
const comments = new schema.Entity("comments", {}, { idAttribute: "_id" });
const posts = new schema.Entity(
"posts",
{ comments: [comments] },
{ idAttribute: "_id" }
);
const normalizedData = normalize(data, [posts]);
return {
...state,
[path]: {
...normalizedData,
loading: false,
},
path,
};
}
这是我在状态正常化后得到的结果:
{
posts: {
'/explore': {
entities: {
comments: {
'60af0278f7d50458b4521d18': {
_id: '60af0278f7d50458b4521d18',,
body: 'hhfhfhh',
updatedAt: '2021-05-27T02:22:48.667Z',
__v: 0,
replies: [
{
_id: '60af0289f7d50458b4521d19',
body: '1',
timestamp: 1622082185728,
createdAt: '2021-05-27T02:23:05.729Z',
}
],
likesCount: 0,
isLiked: false
},
'60af028ef7d50458b4521d1a': {
_id: '60af028ef7d50458b4521d1a',
body: '2',
updatedAt: '2021-05-27T02:23:10.968Z',
replies: [
{
_id: '60af0296f7d50458b4521d1b',
body: '2',
createdAt: '2021-05-27T02:23:18.809Z',
}
],
}
},
posts: {
'60af026ef7d50458b4521d17': {
_id: '60af026ef7d50458b4521d17',
body: 'Normalizes input data per the schema definition provided.',
comments: [
'60af0278f7d50458b4521d18',
'60af028ef7d50458b4521d1a'
]
}
}
},
result: [
'60af026ef7d50458b4521d17'
],
loading: false
},
path: '/explore'
}
}
我尝试将其非规范化,但迄今为止没有成功:
import _ from "lodash";
import { denormalize, schema } from "normalizr";
export const postSelector = ({ posts }) => {
if (_.isEmpty(posts)) {
return [];
}
const comments = new schema.Entity("comments", {}, { idAttribute: "_id" });
const mySchema = { posts: [comments] };
const data = denormalize(
posts[posts.path].result,
mySchema,
posts[posts.path].result.entities
);
return {
[posts.path]: data,
};
};
这就是我得到的:
'/explore': {'60af0278f7d50458b4521d18'}