我是 React 的新手,正在尝试从 API 中提取一些信息,但在使用 .map 函数将检索到的数据传递到数组中时,总是出现此错误:
TypeError: items.map is not a function.
我对 JavaScript 不太熟悉,所以我不完全理解这里发生了什么。我已经包含了我的代码:
import React, { Component } from "react";
import "./App.css";
class App extends Component {
constructor() {
super();
this.state = {
items: [],
isLoaded: true
};
}
componentDidMount() {
fetch("http://www.colr.org/json/colors/random/7")
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
items: json
});
});
}
render() {
var { items, isLoaded } = this.state;
var itemInfo = items.map(item => (
<div key={item.colors.id}>Hex:{item.colors.hex}</div>
));
if (!isLoaded) {
return <div>{itemInfo}</div>;
} else {
return <div className="App">{itemInfo}</div>;
}
}
}
export default App;
最佳答案
自 items
state 中的数组最初是一个空数组,更改 items
时会出现此错误到不是数组的东西。
查看您问题中 API 的响应,解析后您将从 JSON 中获取一个对象。您要在响应中使用的数组位于 colors
下属性,并且此数组中的每个元素都有 id
和 hex
属性。
class App extends Component {
// ...
componentDidMount() {
fetch("http://www.colr.org/json/colors/random/7")
.then(res => res.json())
.then(res => {
this.setState({
isLoaded: true,
items: res.colors
});
});
}
render() {
var { items, isLoaded } = this.state;
var itemInfo = items.map(item => <div key={item.id}>Hex:{item.hex}</div>);
// ...
}
}
关于javascript - 使用 React 和 API 时如何修复 "TypeError: items.map is not a function"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55081822/