使用这段代码,我能够检索用户的数据并对其进行console.log,但无法将其传递或获取到数据数组中,无法使用data.map来呈现用户的信息,因为它是console.logs空数组,并抛出一个错误: Uncaught (承诺) TypeError: data.map不是函数。如何将这些数据获取到数据数组?提前感谢!
import React, { useState, useEffect } from 'react';
import './welcome.css';
function Welcome (){
const [data, setUsers] = useState([])
useEffect(() => {
fetch('http://localhost:4000/users')
.then((res) => res.json())
.then(users => setUsers({users}, console.log(users), console.log(data)))
}
)
return(
<div className='welcome'>
<ul >
{data.map(user =>
<li className='user' key={user._id}>{user.Username}</li>
)}
</ul>
<h1>Welcome to GRM</h1>
<h1>Explore the music world</h1>
</div>
)
}发布于 2022-03-11 11:18:46
如果users是一个数组,那么只需要将users传递给setUsers
import React, { useState, useEffect } from "react";
import "./welcome.css";
function Welcome() {
const [data, setUsers] = useState([]);
useEffect(() => {
fetch("http://localhost:4000/users")
.then((res) => res.json())
.then(({ users }) =>
setUsers(users)
);
});
return (
<div className="welcome">
<ul>
{data.map((user) => (
<li className="user" key={user._id}>
{user.Username}
</li>
))}
</ul>
<h1>Welcome to GRM</h1>
<h1>Explore the music world</h1>
</div>
);
}发布于 2022-03-11 11:25:14
拆线
.then(用户=> setUsers({users},console.log(users),console.log(Data)
加上这个
.then ((res)=>{setUsers(res.data)})
我希望它能对你有用
发布于 2022-03-12 10:56:54
对于那些遇到同样问题的人来说,以下是对我有用的方法:
export default function Welcome (){
const [data, setUsers] = useState([])
useEffect(() => {
fetch('http://localhost:4000/users')
.then(res => (res.json()))
.then(({users}) => setUsers((users)))
})
return(
<div className='welcome'>
<ul>
{data.map((user) =>
<li className='user' key={user._id}>
{user.Username}
</li>
)}
</ul>
<h1>Welcome to GRM</h1>
<h1>Explore the music world</h1>
</div>
)
}毫不奇怪,这是一个适当数量的括号问题。从MongoDB检索到的数据如下所示:
{"users":
[{
"_id":"622c6b2e1c9e40c9775a8940",
"Username":"222","Email":"222@gmail.com",
"Password":"$2b$10$OafBy/2M6a3TZOf/Fslv.u/7tREMGJk6BD.GCiul23giaYh58CTfC",
"Lists":[],"__v":0
},
{
"_id":"622c6b491c9e40c9775a8944",
"Username":"111","Email":"111@gmail.com",
"Password":"$2b$10$cpqiLxsW70stj/4P5AGKUucvXyRDha6Fy3bpGsz0vg.1p0ia.7Jwi",
"Lists":[],"__v":0
}
]}https://stackoverflow.com/questions/71437663
复制相似问题