【问题标题】:ReactJS best practice with complex data structures复杂数据结构的 ReactJS 最佳实践
【发布时间】:2017-07-02 00:49:53
【问题描述】:

我正在将 React 集成到现有应用程序中。这个应用程序是数据密集型的,数据结构非常复杂,这让我有点难以适应 React 模式,尤其是无状态和组合。

给定这样的数据:

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'
  },
  ...
}

由于这些数据是通过 id 链接的,因此我有两种可能性:

  1. 在父组件中检索子数据并将其传递给子组件。

  2. 传递 ID,子级检索它自己的数据。

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

我的另一个问题是,将 Choice 作为其 props 的组件是否应根据其 Choice 的类型以不同的方式显示,是制作这样的包装组件的更好方法吗? :

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

或者有没有更清洁的选择(我对switch case有点过敏)...

【问题讨论】:

    标签: javascript oop reactjs


    【解决方案1】:

    宣传您的第一个问题:

    我会选择第一个解决方案,即检索父级中的数据。如果您选择更容易(它将仅在一个地方处理),这将转向某种状态管理 (redux)。

    广告您的第二个问题:

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

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

    潜在的优势是这种选择——组件映射可以在多个组件之间共享而无需复制,您可以将其存储在模块中并在需要时导入。

    【讨论】:

    • 谢谢,这证实了我的想法!关于迁移到 Redux,您认为它可以适应深度链接的数据结构吗?
    • 根据 redux 的创建者 Dan Abramov 的说法,它更适合浅层状态树。欲了解更多信息,我不能推荐他的egghead course,这是一个很好的学习资源
    猜你喜欢
    • 1970-01-01
    • 2011-07-21
    • 2021-12-29
    • 2016-09-21
    • 2023-04-08
    • 1970-01-01
    • 2017-09-03
    • 2011-10-16
    • 1970-01-01
    相关资源
    最近更新 更多