ReactJS“未处理的拒绝(TypeError):this.state.features.map 不是函数"

2022-01-20 00:00:00 reactjs fetch javascript ecmascript-6

我正在学习 React,现在我正在尝试使用 map 执行 get 请求和列表,但是当我运行此代码时,他们会遇到此错误Unhandled Rejection (TypeError): this.state.features.map不是函数".我已经搜索过这个,但我不明白发生了什么.

I'm learning React and now I'm trying to do a get request and list with map but when I run this code they come up with this error "Unhandled Rejection (TypeError): this.state.features.map is not a function". I have already searched this but I do not understand what is going on.

   import React, { Component } from 'react';
import './App.css';

class App extends Component {

  constructor() {
    super();
    this.state = {
      features: [{
        id: 1,
        name: 'Test',
        count: 1
      }]
    }
  }

  componentWillMount() {
    fetch("http://demo6085176.mockable.io/features")
      .then(response => response.json())
      .then(json => {
        console.log(json);
        this.setState({
          features: json,
        });
      });
    console.log(this.state.features)
      
  }

  render() {
    return (
      <div className="App">
        <ul>
          {
            this.state.features.map(function(feature){
              return (
                <li key={feature.id}><button type="button">Upvote</button> ({feature.count}) <span>{feature.name}</span></li>
              )
            })
          }
        </ul>
      </div>
    );
  }
}

export default App;

推荐答案

在你的componentWillMount中,这样做:

In your componentWillMount, just do this:

componentWillMount() {
   fetch("http://demo6085176.mockable.io/features")
    .then(response => response.json())
    .then(json => {
      console.log(json);
      this.setState({ features: json.features });
   });
}

您从 API 获得的响应是​​一个对象,该对象具有 features 键,该键是您想要的数据对象的数组.

The response you get from the API is an object which has a key of features which is an array of objects of the data you want.

相关文章