I am making a call to firebase database and parsing through the JSON objects and storing them in an array locally. Then I am copying the array created to a state array object and later printing the values of the state array object inside the render() function.
class ABC extends Component
{
state = {
objectArray:[
{
key1:'',
key2:'',
key3:'',
key4:''
}
]
};
componentDidMount() {
var objectArray = [];
var object = {
key1:'',
key2:'',
key3:'',
key4:''
};
// parsing through the firebase object and storing it in the object which is happening successfully
objectArray.push(object);
//when I print the array it gives me the result: [object Object],[object Object] which means two objects are getting stored here.
this.setState({objectArray: objectArray });
}
render()
{
this.state.objectArray.map(function(item){
console.log("The items is "+item.key1); // No data getting printed here.
console.log("The items is "+item.key2);
console.log("The items is "+item.key3);
console.log("The items is "+item.key4);
});
}
我能够从firebase对象数组中获取结果并进行解析,并将其存储在objectArray本地对象中,但无法将其存储在状态数组对象中。这里出了什么问题?
您可以这样做:
this.state.objectArray.map( (item)=> return {
console.log("The items is "+item.key1); // No data getting printed here.
console.log("The items is "+item.key2);
console.log("The items is "+item.key3);
console.log("The items is "+item.key4);
})
您的渲染方法应如下所示,因为您需要返回一些JSX。
render() {
this.state.objectArray.map(function (item) {
console.log("The items is " + item.key1); // No data getting printed here.
console.log("The items is " + item.key2);
console.log("The items is " + item.key3);
console.log("The items is " + item.key4);
});
return this.state.objectArray.map(item => <p>{item.key1}</p>)
}
请注意,所有值都是空字符串,因此请确保它们不是空字符串。
更新:
根据我在提供的文件中看到的信息,我想您是在实际接收数据之前设置状态。尝试在回调中设置状态:
componentDidMount() {
const objectArray = [];
const object = {
key1: '',
key2: '',
key3: '',
key4: ''
};
objectsRef.on('value', (snapshot) => {
snapshot.forEach(function (childSnapshot) {
objectsRef.child(childSnapshot.key).on('value', function (childData) {
object.key1 = childData.val().key1;
object.key2 = childData.val().key2;
object.key3 = childData.val().key3;
object.key4 = childData.val().key4;
objectArray.push(object);
this.setState({ objectArray: objectArray });
console.log("objectArray array is " + objectArray.toString());
})
});
});
}
最好进行修改,以使setState
仅被调用一次,而不是每次迭代都被调用。