繁体   English   中英

如何在reactjs中将数据数组从一个组件传递到另一个组件

[英]How to pass array of data from one component to another component in reactjs

我试图将数据数组从父组件传递到子组件,但在子组件中我没有得到数据数组。请您纠正我做错的地方。

在父组件中,我从服务中获取数据: var tableNames = [DataService.getTableNames()]; 将数组传递给子组件: <DataQueryInterface tableNames={[tableNames]}/>在子组件中,我试图像这样解构: var tableNames = [props.tableNames]

你能帮我解决这个问题吗...

以下是我建议如何构建它:

var tableNames = [ DataService.getTableNames() ]; // Data returned by the function is the placed inside a new `[]`

如果DataService.getTableNames()本身返回一个数组,那么您可以直接将其分配给tableNames如下所示:

var tableNames = DataService.getTableNames(); // no need to wrap that inside another []

清除后,将数组传递给子组件将如下所示:

<DataQueryInterface tableNames={tableNames}/> 

在子组件中,您可以像下面这样解构:

var { tableNames } = props;
// tableNames now contains reference to passed on `[]` from parent.

注意props是一个包含属性名称tableNames的对象,其中包含对数组的引用。

如果DataService.getTableNames()返回一个数组,您应该像这样分配它var tableNames = DataService.getTableNames(); 然后将其传递给组件<DataQueryInterface tableNames={tableNames}/>

下面是一个简单的例子,给出了我们对需求的了解:

class DataService {
  getTableNames() {
    return ['John', 'Doe'];
  }
}
class Child extends React.Component {
  render() {
    const tableNames = this.props.tableNames;
    console.log('child names', tableNames)
    return (<div>{tableNames}</div>);
  }
}
class Parent extends React.Component {
  constructor() {
    super();
    const service = new DataService();
    this.tableNames = service.getTableNames();
    console.log('parent names', this.tableNames);
  }

  render() {
    return (<Child tableNames={this.tableNames}/>);
  }
}

React.render(<Parent />, document.getElementById('app'));

这里还有一个有效的 jsfiddle https://jsfiddle.net/Lh54mfwa/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM