我正在尝试将从我的服务器获取的对象列表传递到状态列表。当我打印出来时,我看到列表中没有值,或者有时它说它是未定义的。为什么会发生这种情况,我该如何解决?谢谢。
const favContext = useContext(FavoritesContext);
const participantContext = useContext(ParticipantsContext);
let [allPossibleParticipants, setAllPossibleParticipants] = useState([]);
let [allParticipants, setAllParticipants] = useState([]);
let [showParticipants, setShowParticipants] = useState(false);
useEffect(() => {
try {
fetch('http://localhost:3000/users')
.then(response => {
return response.json();
}).then(data => {
const users = [];
for (const key in data) {
const user = {
id: key,
...data[key]
};
users.push(user);
};
console.log(users);
setAllPossibleParticipants(users);
console.log(allPossibleParticipants);
})
} catch (err) { console.log(err) };
}, [participantContext, props]);```
**Print Output:**
Original object
{
"id": "1",
"_id": "60e5f9464711a474ccd0b592",
"name": "Juan",
"email": "juan.ucf.edu",
"username": "juanucf1",
"__v": 0
}
Receiving List
[]
答案 0 :(得分:1)
setState 是异步的,可能没有在您的 console.log 语句之前更新。 尝试将您的 console.log 移到 useEffect 挂钩之外以查看您的状态更新。
或者,您也可以使用另一个 useEffect 钩子,它会在状态更改时触发以查看更新的状态:
let [allPossibleParticipants, setAllPossibleParticipants] = useState([]);
let [allParticipants, setAllParticipants] = useState([]);
let [showParticipants, setShowParticipants] = useState(false);
useEffect(()=>{
console.log(allPossibleParticipants)
},[allPossibleParticipants])
/// rest of your code
答案 1 :(得分:1)
这是因为 useEffect
处理程序在其创建时设置的 allParticipants
值上被关闭。因此,每当您引用 allParticipants
时,您都会获得相同的值 - 它永远不会通过 setter 更新。