如何将大量数据从父组件传递到子组件

时间:2018-10-21 00:10:41

标签: reactjs redux

说我有一个像这样的父组件:

class ParentComponent{
    constructor(props){
        this.state = {
            children:[{...},{...}...]
        }
     render(){
         return(
             <ChildComponentList .../>
         )
     }
    }
}

还有这样的子列表:

class ChildComponentList{
    constructor(props){
        this.state = {
            ...
        }
     render(){
         return(
             ???.children.map(
                 <ChildComponent ... />
             )
         )
     }
    }
}

现在,我显然希望将孩子从父级传递到孩子列表。我知道您使用道具将数据从父母传递给孩子。但是说<ChildComponentList children = {this.children} />之类的东西对我来说没有任何意义,因为孩子不是一个单一的价值而是一个庞大的清单。还要假设这将是一棵树,其中ChildComponent可以包含更多ChildComponentList,依此类推。

以下是我可以看到的选项:

  • 父级中有某种getChildren()方法,子级列表中会调用它
  • 使用Redux并将子级放入数据存储区
  • 让每个子组件列表分别从数据库中检索其数据,这样我就不必在树上传递大列表了
  • 即使对我来说没有意义,只要将整个清单放在道具中

最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

class ParentComponent{

    constructor(props){

        super(props);

        this.state = {
            items:[{...},{...}...]
        }
     }

     render(){
         return(
             <ChildComponentList items={this.state.items} />
         )
     }
}


class ChildComponentList{
     render(){
         return(
             this.props.items.map(
                 (item, i) => <ChildComponent key={i} ... />)
         )
     }
}