我正在使用normalizr来规范化响应。
我的问题是我不知道如何管理规范化的响应。
{
result:[]
entities: {
words: {
//...
1: {
definitions: [1, 2, 3]
}
// other word objects...
},
definitions: {
1: 'blah blah'
2: 'blah blah'
3: 'blah blah'
// definition objects
}
}
}
我想将这些词语传递给带有定义的反应组件。如何检索具有嵌套定义的单词并将其呈现给我的组件。
答案 0 :(得分:1)
<强> webpackbin DEMO 强>
假设您的州看起来像这样
entities: {
words: {
//...
1: {
id:1,
text:"Word",
definitions: [1, 2, 3]
},
// other word objects...
},
definitions: {
1: {id:1, text:'blah blah'},
2: {id:2, text:'blah blah'},
3: {id:3, text:'blah blah'},
// definition objects
}
},
wordsById : [1,4,7,8,22]
然后...... WordList可能看起来像这样。从状态切片ID,以呈现列表
const WordList = ({ids}) => <div>{ids.map(id => <Word id={id} key={id}/>)}</div>;
export default connect(state =>({ ids:state.wordsById }))(WordList);
和Word组件:从道具中通过id获取特定单词,通过地图计算定义列表
const Word = ({word, definitions}) =>(
<div className="word-block">
<span>{word.text}</span>
<DefinitionsList definitions={definitions}/>
</div>
)
const mapStateToProps = (state, props) =>{
const word = state.entities.words[props.id];
const { definitions:ids } = word
return {
word,
definitions:ids.map(id => state.entities.definitions[id])
};
}
export default connect(mapStateToProps, actions)(Word);
和DefinitionsList
const DefinitionsList = ({definitions})=> (
<div className="definitions">
{definitions.map(def =><div key={def.id}>{def.text}</div>)}
</div>
);
功能组件仅用于简短。