【发布时间】:2017-10-06 15:54:05
【问题描述】:
您好,我正在尝试在数组中解析此对象:
[ { address: '15 rue de Bouvines',
category: 'Bar',
city: 'Tours',
storeName: 'La Tabtiere',
_key: '-KuVBzIx8rFZxneg5JvY' },
{ address: '',
category: '',
city: '',
storeName: '',
_key: '-KuVTSgauvHcvhDigNVz' } ]
这是我初始化东西和尝试解析数组的代码:
constructor(props){
super(props);
this.tasksRef = firebase.database().ref('/store');
this.state = {
user:null,
loading: true,
newTask: ""
}
}
componentDidMount() {
// start listening for firebase updates
this.listenForTasks(this.tasksRef);
}
//listener to get data from firebase and update listview accordingly
listenForTasks(tasksRef) {
tasksRef.on('value', (dataSnapshot) => {
var tasks = [];
dataSnapshot.forEach((child) => {
tasks.push({
address: child.val().address,
category: child.val().category,
city: child.val().city,
storeName: child.val().storeName,
_key: child.key
});
});
this.setState({
tasks:tasks
});
});
}
this.setState({tasks:tasks}, function(this.state.tasks) {
ParseArray() {
return this.state.tasks.map(function(result, i){
return(
<View key={i}>
<Text>{result.address}</Text>
<View>
<Text>{result.storeName}</Text>
</View>
</View>
);
});
}
}
);
并尝试使用这种方式显示:
render() {
return(
<View>
test
{this.ParseArray()}
</View>
)
}
但是我在 xcode 中遇到了这个错误:
undefined 不是对象(评估 'this.state.tasks.map')
有什么想法吗?
谢谢
【问题讨论】:
-
请显示设置任务的代码。
-
我已经更新了我的代码
-
我怀疑 listenForTasks 未定义,因为它未绑定。你有几个选项来绑定它。函数声明中的箭头函数,在构造函数中绑定函数,并在其用例中绑定。只需在构造函数中添加:
this.listenForTasks = this.listenForTasks.bind(this);
标签: arrays parsing object react-native