【问题标题】:What's the best way to deal with a normalized response?处理标准化响应的最佳方法是什么?
【发布时间】:2016-11-24 09:56:05
【问题描述】:

我正在使用 normalizr 来规范化响应。

我的问题是我不知道如何管理标准化响应。

{
  result:[]
  entities: {
    words: {
      //...
      1: {
       definitions: [1, 2, 3]
      }
      // other word objects...      
    },
    definitions: {

      1: 'blah blah'
      2: 'blah blah'
      3: 'blah blah'
      // definition objects
    }
  }
}

我想将单词传递给带有定义的反应组件。如何检索具有嵌套定义的单词并将其呈现给我的组件。

【问题讨论】:

    标签: javascript reactjs redux react-redux normalizr


    【解决方案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);
    

    and Word 组件:通过 props 中的 id 从 state 中获取特定单词,通过 map 计算定义列表

    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);
    

    和定义列表

    const DefinitionsList = ({definitions})=> (
        <div className="definitions">
            {definitions.map(def =><div key={def.id}>{def.text}</div>)}
        </div>
    );
    

    Functional component 只是简称。

    【讨论】:

      猜你喜欢
      • 2019-10-25
      • 1970-01-01
      • 1970-01-01
      • 2010-09-06
      • 2012-08-23
      • 2010-10-18
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多