我正在尝试在选择器(react-native(中显示数据,但是如果我尝试映射this.state.dataSource,则会显示上述错误我不明白似乎是什么问题
我已经在 Stackoverflow 上尝试了几乎所有相同类型的问题,但似乎都没有奏效
constructor() {
super()
this.state = {
dataSource: [],
PickerValueHolder: '',
}
}
componentDidMount() {
var path = RNFS.DocumentDirectoryPath + '/defects/' + 'defects'+ '.json';
console.log(path);
// write the file
return RNFS.readFile(path, 'utf8')
.then((success) => {
newData = JSON.parse(success);
dataSource = newData[0].results.recordset;
dataSource = JSON.stringify(dataSource)
console.log("datasource "+dataSource);
this.setState({
isLoading: false,
dataSource
});
})
.catch((err) => {
console.log(err.message);
});
}
console.log("数据源"+数据源(;输出
[{"success":true,"results":{"recordsets":[[{"DefectID":2,"Defect":"Damage","Description":"Crack in walls"}]],"recordset":[{"DefectID":2,"Defect":"Damage","Description":"Crack in walls"}],"output":{},"rowsAffected":[1],"returnValue":0}}]
选取器代码
<Picker
selectedValue={this.state.PickerValueHolder}
style={{ height: 50, width: 100 }}
onValueChange={
(itemValue, itemIndex) => this.setState({ PickerValueHolder: itemValue })}
>
{console.log("Picker " + this.state.dataSource)}
{this.state.dataSource.map((item, key) => {
<Picker.Item label={item.defect} value={item.defect} key={key} />
}
)}
</Picker>
{console.log("Picker " + this.state.dataSource(} 输出
[{"DefectID":2,"Defect":"Damage","Description":"Crack in walls"}]
类型错误:无法读取未定义的属性"映射">
预期输出:数据应该在选取器中膨胀
由于 RNFS.readFile(path, 'utf8')
是异步的,因此很可能在填充this.state.dataSource
之前调用 render 方法。 this.state.dataSource
最初将null
,因此您需要在constructor
中进行设置。
// ...
constructor() {
this.state = {
dataSource: []
}
}
更新
在你的问题中,你正在串dataSource
并在州内断言。 Strings
JavaScript 中没有 map
函数,因此请删除有问题的代码,如下所示。
return RNFS.readFile(path, 'utf8')
.then((success) => {
newData = JSON.parse(success);
dataSource = newData[0].results.recordset;
console.log("datasource "+JSON.stringify(dataSource));
this.setState({
isLoading: false,
dataSource
});
})
.catch((err) => {
console.log(err.message);
});