【问题标题】:React - error result map is not a function?React - 错误结果图不是函数?
【发布时间】:2020-10-02 15:22:08
【问题描述】:
  • 框架:反应
  • 错误类型:result.map 不是函数

我正在按照《学习 React 之路》一书,我尝试使用黑客新闻 API 编写以下代码,它运行良好,但无法使用此 API。我不知道为什么会出现这个错误,请帮忙。

链接到我的沙盒 --> https://codesandbox.io/s/react-setup-forked-q0hti?file=/src/App.js

import React, { Component } from "react";
    
// API chunks
const PATH_BASE = "https://jsonplaceholder.typicode.com/todos";
const PATH_SEARCH = "/search";
const PARAM_SEARCH = "query=";
const DEFAULT_QUERY = "redux";
    
//const url = `${PATH_BASE}${PATH_SEARCH}?${PARAM_SEARCH}${DEFAULT_QUERY}`;
//console.log(url);
    
class App extends Component {
  constructor() {
    super();
    this.state = {
      result: null
    };
    this.hitStories = this.hitStories.bind(this);
  }
   
  // handling the local state value
  hitStories(result) {
    this.setState({
      result
    });
  }
    
  // lifecycle method
  // Note: componenetDidMount runs after the render method
  componentDidMount() {
    fetch(`${PATH_BASE}${PATH_SEARCH}?${PARAM_SEARCH}${DEFAULT_QUERY}`)
      .then((response) => response.json())
      .then((json_result) => this.hitStories(json_result))
      .catch((error) => error);
  }

  render() {
    console.log(this.state)
    const { result } = this.state;

    if (!result) {
      return null;
    }
    
    return (
      <div>
        <h2>Fetch API in React</h2>
        {result.map((
          item 
        ) => (
         <div>
           {item.title}
          </div>
        ))}
      </div>
    );
  }
}
    
export default App;

【问题讨论】:

  • 其实 this.state.result 是一个对象,所以你不能遍历它。
  • result 变量是一个对象,而不是一个数组。您应该将其更改为:Object.values(result).map((item) =&gt; (,这将创建一个包含所有值的数组
  • @szczocik 感谢它修复了错误,但它没有映射标题列表(存在于 api 中)。我错过了什么?
  • @YashMarmat,当你遍历item 时,它的形状是什么?
  • @szczocik 我只是将它用作随机变量,我已经给出了上面沙箱的链接,希望有助于解决我的问题。

标签: reactjs api


【解决方案1】:

.map 用于数组,您的result 不是数组而是对象。试试这个:

render() {
  const { result } = this.state;

  return result ? (
    <div>
      <h2>Fetch API in React</h2>
      { Object.values(result).map((item) => (
        <div>{item.title}</div>
      ))
      }
    </div>
  ): null;
}

【讨论】:

  • 非常感谢,这修复了错误,但它没有映射标题列表(存在于 api 中)。我错过了什么?
猜你喜欢
  • 2019-04-21
  • 2017-08-16
  • 2019-09-21
  • 2018-02-06
  • 2020-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多