2017-02-13 49 views
2

我将React集成到现有的应用程序中。这个应用程序是数据密集型的,数据结构非常复杂,这使我很难适应React模式,尤其是无状态和组合。具有复杂数据结构的ReactJS最佳实践

这样的假设数据:

component: { 
 
    options: [optionA, optionB, optionC] 
 
} 
 

 
options: { 
 
    optionA : { 
 
    name: 'FOO', 
 
    choices: [choiceA, choiceB, choiceC] 
 
    }, 
 
    optionB : { 
 
    name: 'BAR', 
 
    choices: [choiceD, choiceE] 
 
    }, 
 
    ... 
 
} 
 

 
choices: { 
 
    choiceA : { 
 
    type: 'typeA', 
 
    choices: [choiceA, choiceB, choiceC], 
 
    name: 'abb' 
 
    }, 
 
    choiceB : { 
 
    type: 'typeB', 
 
    name: 'abc' 
 
    }, 
 
    ... 
 
}

由于该数据是由IDS链接我有两个可能性:

  1. 检索儿童的数据在父组件,并将其传递给孩子们。

  2. 通过身份证和子女检索自己的数据。

意味着一个动态检索组件道具和其他意味着具有拥有所有必要的数据,这是孩子们的“上帝”的父母,哪一个才是更好的方法?

我的另一个问题是,如果选择Choice作为其道具的组件应该根据它的选择类型显示不同,是制作像这样的包装组件的更好方法吗? :

class Choice extends Component { 
 
    constructor(props){ 
 
    super(props); 
 
    } 
 
    
 
    render(){ 
 
    switch(props.choice.type){ 
 
     case "typeA": 
 
     return (<TypeAComponent />); 
 
     case "typeB": 
 
     return (<TypeBComponent />); 
 
     default: 
 
      return (..); 
 
    } 
 
    } 
 
}

或者是有一个更清洁的替代(我有点过敏切换的情况下)...

回答

3

广告你的第一个问题:

我会选择第一个解决方案,即检索父数据。如果你选择这么容易(这将只在一个地方处理),这将转移到某种状态管理(redux)。

广告你的第二个问题:

您可以使用字典摆脱开关:

const choiceRenderers = { 
    "typeA":() => <TypeAComponent />, 
    "typeB":() => <TypeBComponent />, 
    // etc. 
}; 

class Choice extends Component { 
    render() { 
     const renderer = choiceRenderers[this.props.choice.type]; 
     return renderer 
      ? renderer() 
      : <DefaultChoice />; 
    } 
} 

的潜在优势是,这种选择分量映射可以跨多个组件共享,不复制它,您可以将其存储在模块中并在需要时导入它。

+0

谢谢,这证实了我的想法! 关于迁移到Redux,你认为它适用于深度链接的数据结构吗? –

+1

根据redux的创建者Dan Dan Abramov(http://stackoverflow.com/users/458193/dan-abramov),它对浅层状态树更好。欲了解更多信息,我不能推荐他的[egghead当然](https://egghead.io/lessons/javascript-redux-normalizing-the-state-shape),这是一个很好的学习资源 –