【发布时间】:2021-11-07 16:10:29
【问题描述】:
我创建了这个 React 应用程序来练习 fetch API。 但是,在编写代码以通过 map 方法在浏览器上显示数据时,我收到错误消息“TypeError: profile.map is not a function”。下面是代码:
import React, { Fragment, useEffect, useState } from "react";
import "./App.css";
function App() {
// https://reqres.in/api/users
const [profile, setProfile] = useState([]);
const [loading, setLoading] = useState(false);
const getProfile = async () => {
setLoading(true);
const response = await fetch("https://reqres.in/api/users");
const data = await response.json();
setProfile(data);
setLoading(false);
};
useEffect(() => {
getProfile();
}, []);
return (
<Fragment>
<h1>React fetch</h1>
<div className="main">
<section className="section">
<h2>Get database</h2>
<div>
{loading ? (
<Fragment>loading..</Fragment>
) : (
profile.map(i => {
<Fragment>
<ul>
<li>{i.id}</li>
<li>{i.email}</li>
<li>{i.first_name}</li>
<li>{i.last_name}</li>
<li>
<image src={i.avatar} />
</li>
</ul>
</Fragment>;
})
)}
</div>
</section>
<form className="section">
<h2>Post data</h2>
<input type="text" placeholder="enter detail" />
<button type="submit">Post</button>
</form>
<form className="section">
<h2>Update data</h2>
<select>
<option>Choose data</option>
</select>
<input type="text" placeholder="enter detail" />
<button type="submit">Update</button>
</form>
</div>
</Fragment>
);
}
export default App;
为什么无法识别地图?
【问题讨论】:
-
因为
setProfile(data);中的data不是数组。如果你把data的回复贴在这个问题里,我相信你会发现的。 -
@choz 这个项目只有一页,API来自“reqres.in/api/users”
-
仔细查看您提供的网址。那不是数组。
标签: reactjs fetch crud fetch-api