我的状态为数组时间,并且其中包含数据。我要做的是通过此状态进行映射并使用props调用子组件
我的状态
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);
})
}
退回零件
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", … }
有什么想法吗?在此先感谢
答案 0 :(得分:5)
您能否传递feed.feedid而不是feed.id并在map函数之前返回。
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;
}
}
希望它应该能工作
答案 1 :(得分:1)
var customerAttribute =
[ {attributeId: 1, attributeName: "FirstName", attributeType: "String", isMandatory: false},
{attributeId: 2, attributeName: "LastName", attributeType: "String", isMandatory: false},
{attributeId: 3, attributeName: "DateOfBirth", attributeType: "Date", isMandatory: false},
{attributeId: 4, attributeName: "Email Address", attributeType: "String", isMandatory: false},
{attributeId: 5, attributeName: "Mobile Number", attributeType: "Number", isMandatory: false},
{attributeId: 6, attributeName: "Address Line 1", attributeType: "String", isMandatory: false},
{attributeId: 7, attributeName: "Address Line 2", attributeType: "String", isMandatory: false},
{attributeId: 8, attributeName: "City", attributeType: "String", isMandatory: false}]
for (let index = 0; index < customerAttribute.length; index++) {
console.log(customerAttribute[index].attributeId)
console.log(customerAttribute[index].attributeName)
}
feed.id 等效于this.state.feedArray.map((feed,id)=>{
console.log(feed.body);
return (<FeedElement id={id} body={feed.body}/> ); Works
})
,如果对象数组中不存在 id ,则对其进行访问将抛出 undefined >,但是在您提供的feed[id]
具有feed
的console.log中,您可以传递feed.feedid
或id={feed.feedid}