我有2个组件,一个父组件和一个子组件在React。我正在从父组件中的API获取数据,我想把它传递给子组件。数据成功获取,我可以在console.log()中查看数据。数据随后存储在父级的状态(我也已经验证并在控制台日志中查看了它。
根据数据中的数组数量,我希望创建相应数量的子组件。
我最初使用这个功能
{
this.state.tables.map((item) => (
<App data = {this.state.tables} />
))
}
尝试将数据映射到我的子组件。当数据未通过时,我尝试将数组(从我的状态)简单地传递给我的子组件
<App data={this.state.tables}/> //App here is my child component
但是没有用。当我打开控制台日志时
props
在我的子组件中,这是我得到的,我试图传递的道具数据没有传递
{history: {…}, location: {…}, match: {…}, staticContext: undefined}
history: {length: 7, action: "POP", location: {…}, createHref: ƒ, push: ƒ, …}
location: {pathname: "/table", search: "", hash: "", state: undefined, key: "bixd4p"}
match: {path: "/table", url: "/table", isExact: true, params: {…}}
staticContext: undefined
__proto__: Object
当我console.log(props.data)的构造函数或组件的子组件,我得到
undefined
为什么我的子组件无法使用此文件访问数据。道具。数据
下面是我的父组件和子组件的代码,以便更好地参考
父母亲
render(){
return (
<div>
{
this.state.tables.map((item) => (
<App data = {this.state.tables} />
))
}
<App data={this.state.tables}/>
<Button style = {{marginTop : 80, marginRight : 30, float : "right"}} variant="contained" color="primary" onClick={() => this.addnewtable()}>
Add New Table
</Button>
</div>
);
}
小孩
constructor(props) {
super(props)
console.log("constructor", this.props)
console.log("props", this.props.data)
this.state = {
users: [],
message: null
}
this.reloadUserList = this.reloadUserList.bind(this);
}
试试这个。
this.state.tables.map( item => (
<App key = {<Some unique value>} data = {item} />
));