我创建了这个 React 应用程序来练习 fetch API。 但是,在编写代码以通过map方法在浏览器上显示数据时,我收到错误消息“TypeError:profile.map不是函数”。下面是代码:
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;
为什么地图无法识别?
我相信这是因为 .map 是数组原型的方法,而不是对象的方法(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
您可以使用 data.data 而不仅仅是 data 从对象返回数组:
...
const getProfile = async () => {
setLoading(true);
const response = await fetch("https://reqres.in/api/users");
const data = await response.json();
setProfile(data.data); // probably a safer way to do this, but if you console.log(data) you'll see an object is being returned, not an array.
setLoading(false);
};
...
所以,
const data = await response.json();
执行此行后,我们在数据常量中得到的结果是一个对象。我们只能在数组(特别是数组原型)上使用 MAP 函数,而不能在对象上使用。而且您实际搜索的配置文件数据位于数据“constant”的“data”键内。因此,在设置配置文件数据时,只需使用 setProfile(data.data);
。
Map 需要返回一个值。
{loading ? (
<Fragment>loading..</Fragment>
) : (
profile.map(i => {
return (
<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>;
)
})
)}
此外,您不能在对象上使用映射函数。看起来您的响应是一个对象,您正在寻找的是响应中的数据。试试这个...
setProfile(data.data);