[英]How to fix “TypeError: items.map is not a function” when working with React and APIs?
我是React的新手,正在尝试从API提取一些信息,但是在使用.map函数将检索到的数据传递到数组时,始终会收到此错误:
TypeError:item.map不是函数。
我对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
数组最初是一个空数组,因此将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>);
// ...
}
}
就您的特定问题而言,Tholle是绝对正确的……我将进一步清理您的代码,如下所示:
import React, { Component } from 'react';
class App extends Component {
state = { items: [], isLoading: true, error: null };
componentDidMount() {
fetch('http://www.colr.org/json/colors/random/7')
.then(res => res.json())
.then(json => {
this.setState({
isLoading: false,
items: json.colors,
});
})
.catch(error =>
this.setState({ error: error.message, isLoading: false }),
);
}
renderColors = () => {
const { items, isLoading, error } = this.state;
if (error) {
return <div>{error}</div>;
}
if (isLoading) {
return <div>Loading...</div>;
}
return (
<div>
{items.map(item => (
<div key={item.id}>Hex: {item.hex}</div>
))}
</div>
);
};
render() {
return <div>{this.renderColors()}</div>;
}
}
export default App;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.