我刚刚开始在 Redux 中使用 normalizr,我被困在我看来像一个简单的问题上,但我可能做错了。所以我想对这样的数组进行规范化:
{
articles: [
{id: 1, someValue: 'test'},
{id: 2, someValue: 'test2'}
]
}
变成这样的结构:
{
result: {
articles: [1,2]
},
entities: {
articles: {
1: {someValue: 'test'},
2: {someValue: 'test2'}
}
}
}
我试过这样做:
const article = new Schema('articles');
responce = normalize(responce, {
articles: arrayOf(article)
});
但这给了我一个看起来像这样的结构:
{
articles: {
entities: {},
result: {
0: {someValue: 'test'},
1: {someValue: 'test2'}
}
}
}
现在没有文章 ID 数组。我假设我在这里遗漏了一些东西:
article.define({
...
});
但无法弄清楚在这个简单的情况下需要去那里
最佳答案
您不必定义文章。确保您已从 normalizr
导入所有内容正确。我试过你的代码,它给了我预期的结果:
import { normalize, Schema } from 'normalizr';
let response = {
articles: [
{ id: 1, someValue: 'test' },
{ id: 2, someValue: 'test2' }
]
};
const article = new Schema('articles');
response = normalize(response, {
articles: [article]
});
console.log(response);
输出:
{
result: {
articles: [1,2]
},
entities: {
articles: {
1: {someValue: 'test'},
2: {someValue: 'test2'}
}
}
}
关于redux - 使用 normalizr 规范化简单数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35852893/