在 ReactJs 的 Map 函数中调用子组件
Calling A Child Component Inside a Map Function In ReactJs
我有一个数组时间状态并且有数据在 it.what 我想做的是通过这个状态映射并使用道具
调用子组件
我的状态
this.state = {
user:'',
feedArray:[],
}
设置数据的函数
//I CALLED THIS IN COMPONENTDIDMOUNT
renderFeed(){
rdb.ref("feeds").once('value',(snapshot)=>{
snapshot.forEach((childSnapshot)=>{
this.setState({feedArray:Object.values(childSnapshot.val())})
})
}).then(()=>{
console.log(this.state.feedArray);
})
}
return部分
render() {
if (this.state.feedArray) {
this.state.feedArray.map((feed,id)=>{
console.log(feed.body); //this works fine
return (<FeedElement id={feed.id} body={feed.body}/> ); //This Not Works
})
}
}
这是 console.log(this.state.feedArray)
上的日志
(4) […]
0: Object { author: "AashiqOtp", body: "kkk", feedid: "-M1_6POMRyqRv2tIKrF9", … }
1: Object { author: "AashiqOtp", body: "kkk", feedid: "-M1_6XYaUAlsXlwnAbcp", … }
2: Object { author: "AashiqOtp", body: "f", feedid: "-M1_HB07eh_08OFFRBbO", … }
3: Object { author: "AashiqOtp", body: "we have a new rm", feedid: "-M1d4xwLmSUKA0RZlH-Q", … }
有什么想法吗?提前致谢
你能在 map 函数之前传递 feed.feedid 而不是 feed.id 和 return 吗?
render() {
if (this.state.feedArray) {
return this.state.feedArray.map((feed,id)=>
(<FeedElement id={feed.id} body={feed.body}/> ); //This Not Works
)
}else {
return null;
}
}
希望它能奏效
this.state.feedArray.map((feed,id)=>{
console.log(feed.body);
return (<FeedElement id={id} body={feed.body}/> ); Works
})
feed.id 等同于 feed[id]
并且如果对象数组中不存在 id 那么访问它会抛出 undefined,但是从 console.log 你提供的 feed
有 feed.feedid
,你可以传递 id={feed.feedid}
或 id={id}
我有一个数组时间状态并且有数据在 it.what 我想做的是通过这个状态映射并使用道具
调用子组件我的状态
this.state = {
user:'',
feedArray:[],
}
设置数据的函数
//I CALLED THIS IN COMPONENTDIDMOUNT
renderFeed(){
rdb.ref("feeds").once('value',(snapshot)=>{
snapshot.forEach((childSnapshot)=>{
this.setState({feedArray:Object.values(childSnapshot.val())})
})
}).then(()=>{
console.log(this.state.feedArray);
})
}
return部分
render() {
if (this.state.feedArray) {
this.state.feedArray.map((feed,id)=>{
console.log(feed.body); //this works fine
return (<FeedElement id={feed.id} body={feed.body}/> ); //This Not Works
})
}
}
这是 console.log(this.state.feedArray)
上的日志(4) […]
0: Object { author: "AashiqOtp", body: "kkk", feedid: "-M1_6POMRyqRv2tIKrF9", … }
1: Object { author: "AashiqOtp", body: "kkk", feedid: "-M1_6XYaUAlsXlwnAbcp", … }
2: Object { author: "AashiqOtp", body: "f", feedid: "-M1_HB07eh_08OFFRBbO", … }
3: Object { author: "AashiqOtp", body: "we have a new rm", feedid: "-M1d4xwLmSUKA0RZlH-Q", … }
有什么想法吗?提前致谢
你能在 map 函数之前传递 feed.feedid 而不是 feed.id 和 return 吗?
render() {
if (this.state.feedArray) {
return this.state.feedArray.map((feed,id)=>
(<FeedElement id={feed.id} body={feed.body}/> ); //This Not Works
)
}else {
return null;
}
}
希望它能奏效
this.state.feedArray.map((feed,id)=>{
console.log(feed.body);
return (<FeedElement id={id} body={feed.body}/> ); Works
})
feed.id 等同于 feed[id]
并且如果对象数组中不存在 id 那么访问它会抛出 undefined,但是从 console.log 你提供的 feed
有 feed.feedid
,你可以传递 id={feed.feedid}
或 id={id}