简体   繁体   English

React JS 无法读取未定义的属性“地图”

[英]React JS cannot read property 'map' of undefined

I want to get data from api, and set it in a state, and use it in map to iterate我想从api获取数据,并将其设置为状态,并在map中使用它进行迭代

    const result = await API.getSearch(data);

    if(result.status === 200){
        this.setState({data: result.data, loading: false })
    }

    const result = await API.getSearch(data); // got data successfully

Then:然后:

this.state.data && this.state.data.length > 0 && this.state.data.data.map(function(value, i){

I know this kind of error mean, map didn't get any data, So I used condition, first I check if state return data, then check if data has length, but still get this error.我知道这种错误意味着,地图没有得到任何数据,所以我使用了条件,首先我检查状态是否返回数据,然后检查数据是否有长度,但仍然得到这个错误。 any solution ?任何解决方案?

I guess instead of this我想而不是这个

this.state.data.data.map(function(value, i){

It should be only one time data应该只有一次数据

this.state.data.map(function(value, i){

Look like you haven't initialized data .看起来你还没有初始化data So, During the first rendering, it is undefined .因此,在第一次渲染期间,它是undefined On undefined , map is not exists.Causing this issue.undefinedmap不存在。导致这个问题。

Declare and define data like this below像下面这样声明和定义data

this.state = {
    data: []
}

OR或者

constructor(props) {
    this.state = {
        data: []
    }
}

Use destructure to have default values and make sure the inner data is array使用解构获得默认值并确保内部data是数组

 const { data : { data = [] } = {} } = { data: { data: ['foo', 'bar']} } ; console.log(data.map(x => x + "--").join());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM