TypeError:尽管设置了数据,但this.state.data.map不是函数:[]

时间:2018-08-11 00:51:36

标签: reactjs

我试图将数据存储在需要首先映射的ItemLists组件中。但是得到TypeError: this.state.data.map is not a function

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

componentDidMount() {    
  fetch('items.json')
  .then(function(response) {
    if (response.status >= 400) {
      throw new Error("Bad response");
    }
    return response.json();
  })
  .then(data => {
    console.log(data)
    this.setState({data: data});
  });
}


render() {     
  return (
    <div className="App">
      {this.state.data.map(function(object){
        return (
          <ItemLists key={object.id} data={object}/>
        )
      })}
    </div>
  );
 }
}

如果我将代码更改为:

render() {     
  return (
    <div className="App">
      return (
        <ItemLists data={this.state.data}/>
      )
    </div>
   )
 }

我得到的错误是:Objects are not valid as a React child (found: object with keys {artist, title, level, released, rating}). If you meant to render a collection of children, use an array instead指向this.setState({data: data});

json数据:

  {
    "data": [
      {
        "name": "cnt",
        "level": "12"
      },
      {
        "name": "stewart",
        "level": "6"
      },
      {
        "name": "nic",
        "level": "7"
      }
    ]
  }

2 个答案:

答案 0 :(得分:2)

在完成fetch请求之后,您将处于状态的data数组设置为已解析的JSON对象。由于常规对象没有像数组那样的map方法,因此会出现错误。

您可以将状态data设置为已解析的JSON对象中的data数组。

componentDidMount() {    
  fetch('items.json')
  .then(response => {
    if (response.status >= 400) {
      throw new Error("Bad response");
    }
    return response.json();
  })
  .then(response => {
    this.setState({ data: response.data });
  });
}

答案 1 :(得分:1)

mydata = reshape(new_data,matrix(2:ncol(new_data),3),idvar=1,dir="long", v.names = c('TId', 'W', 'R'), times = c('Morning1', 'Morning2', 'Afternoon1', 'Afternoon2')) head(mydata) Day time TId W R 1.Morning1 1 Morning1 20180502-033-000005 26.36667 5.872583 2.Morning1 2 Morning1 20180503-033-000005 26.44333 5.845980 3.Morning1 3 Morning1 20180507-033-000006 26.20000 5.925373 4.Morning1 4 Morning1 20180508-033-000005 26.28667 6.028747 5.Morning1 5 Morning1 20180510-033-000005 26.43000 5.990187 6.Morning1 6 Morning1 20180511-033-000005 25.87333 5.883473 中使用函数时应使用Arrow function

React Component