[英]Call to API in React - item.map is not a function
I am currently making a hockey application using an API from NHL.我目前正在使用 NHL 的 API 制作曲棍球应用程序。
I am new to React and I always get the mistake item.map is not a function.我是 React 的新手,我总是会犯错误 item.map is not a function。
import React, {Component} from 'react';
class Api extends Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: []
};
}
componentDidMount() {
fetch("https://statsapi.web.nhl.com/api/v1/divisions/1")
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result.items
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
<li key={item.id}>{item.name}</li>
</ul>
);
}
}
}
export default Api
The error is definitely in the render function but I can't seem to be able to fix it!错误肯定在渲染函数中,但我似乎无法修复它!
You are not calling items.map()
anywhere.您没有在任何地方调用items.map()
。 Try this one:试试这个:
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<React.Fragment>
<ul>
{
items.map(item =>
<li key={item.id}>{item.name}</li>
)
}
</ul>
</React.Fragment>
);
}
}
This should work if result.items
is an array.如果result.items
是一个数组,这应该有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.