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

ReactJS quot;Unhandled Rejection (TypeError): this.state.features.map is not a functionquot;(ReactJS“未处理的拒绝(TypeError):this.state.features.map 不是函数)
本文介绍了ReactJS“未处理的拒绝(TypeError):this.state.features.map 不是函数"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 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.

这篇关于ReactJS“未处理的拒绝(TypeError):this.state.features.map 不是函数"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)