React-Native Picker TypeError: Cannot read property 'map' of undefined

React-Native Picker TypeError: Cannot read property 'map' of undefined

我正在尝试在选择器中显示数据(react-native),但如果我尝试映射 this.state.dataSource,则会显示上述错误 我不明白似乎是什么问题

我在 Whosebug 上尝试了几乎所有相同类型的问题,但其中 none 似乎有效

 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("datasource "+数据源);输出

[{"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"}]

错误类型错误:无法读取未定义的 属性 'map'

预期输出:数据应该在选择器中膨胀

因为 RNFS.readFile(path, 'utf8') 是异步的,渲染方法很可能会在 this.state.dataSource 被填充之前被调用。 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);
    });