使用 normalizr 规范化简单数组
Normalizing simple array with normalizr
我才刚刚开始将 normalizr 与 Redux 结合使用,我被困在了一个在我看来很简单的问题上,但我可能做错了。所以我想像这样规范化一个数组:
{
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'}
}
}
}
我才刚刚开始将 normalizr 与 Redux 结合使用,我被困在了一个在我看来很简单的问题上,但我可能做错了。所以我想像这样规范化一个数组:
{
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'}
}
}
}