无法将对象数组传递给usestate列表

6xfqseft  于 2021-09-23  发布在  Java
关注(0)|答案(2)|浏览(359)

我试图将从服务器获取的对象列表传递到状态列表。当我打印出来时,我看到列表中没有值,或者有时它说它是未定义的。为什么会发生这种情况?我该如何解决?谢谢

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

[]
nbnkbykc

nbnkbykc1#

setstate是异步的,在console.log语句之前可能没有更新。尝试将您的console.log移到Useffect挂钩之外,以查看您的状态更新。
或者,您也可以使用另一个useeffect挂钩,该挂钩将在状态更改时触发以查看更新的状态:

let [allPossibleParticipants, setAllPossibleParticipants] = useState([]);
    let [allParticipants, setAllParticipants] = useState([]);
    let [showParticipants, setShowParticipants] = useState(false);

useEffect(()=>{
    console.log(allPossibleParticipants)
},[allPossibleParticipants])

/// rest of your code
pxyaymoc

pxyaymoc2#

因为 useEffect 处理程序在的值上关闭 allParticipants 这是在其创建时设定的。所以,每当你提到 allParticipants 您将获得相同的值-它永远不会通过setter更新。

相关问题