【发布时间】: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) => (,这将创建一个包含所有值的数组 -
@szczocik 感谢它修复了错误,但它没有映射标题列表(存在于 api 中)。我错过了什么?
-
@YashMarmat,当你遍历
item时,它的形状是什么? -
@szczocik 我只是将它用作随机变量,我已经给出了上面沙箱的链接,希望有助于解决我的问题。