React-Native Picker TypeError:无法读取未定义的属性“ map”

时间:2019-05-28 08:18:59

标签: javascript reactjs react-native picker

我正在尝试在选择器(本机)中显示数据,但是如果我尝试映射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(“ datasource” + 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"}]

错误TypeError:无法读取未定义的属性“地图”

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

1 个答案:

答案 0 :(得分:0)

由于RNFS.readFile(path, 'utf8')是异步的,因此很可能在填充this.state.dataSource之前调用render方法。 this.state.dataSource最初为null,因此您需要在constructor内进行设置。

// ...
constructor() {
  this.state = {
    dataSource: []
  }
}

更新

在您的问题中,您要对dataSource进行字符串化并将其声明为state。 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);
    });