ReactJS “Unhandled Rejection (TypeError): this.state.features.map is not a function”

旧时模样 提交于 2021-02-02 09:45:07

问题


I'm learning React and now i'm trying do a get resquest 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 already search this but I'm not undertand what its 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;

回答1:


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 });
   });
}

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.



来源:https://stackoverflow.com/questions/44657581/reactjs-unhandled-rejection-typeerror-this-state-features-map-is-not-a-funct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!