【问题标题】:ReactJS "Unhandled Rejection (TypeError): this.state.features.map is not a function"ReactJS“未处理的拒绝(TypeError):this.state.features.map 不是函数”
【发布时间】:2017-11-23 06:21:11
【问题描述】:

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

   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;

【问题讨论】:

  • console.log(json) 怎么说?
  • 'json' 未定义
  • 您必须等到fetch 完成...设置“正在加载...”之类的内容,然后在获取完成后进行映射
  • 您的问题通过适当的调试解决了。鉴于json 在您console.log 时未定义,那么服务器的输出可能有问题。
  • @AndreLi 不同意,他不需要等到 fetch。

标签: javascript reactjs ecmascript-6 fetch


【解决方案1】:

在您的 componentWillMount 中,只需执行以下操作:

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

您从 API 获得的响应是​​一个对象,其键为 features,它是您想要的数据对象的数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    • 2021-10-14
    • 2020-11-16
    • 2020-05-06
    • 2019-10-27
    • 2020-09-26
    • 2021-04-16
    相关资源
    最近更新 更多