【问题标题】:Cannot pass object array to useState list无法将对象数组传递给 useState 列表
【发布时间】:2021-09-19 15:00:10
【问题描述】:

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

    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

[]

【问题讨论】:

  • 您是否尝试过console.log(data),以检查它是否真的与您期望收到的相符?
  • setAllPossibleParticipants(state => [...state, ...users]);

标签: javascript arrays reactjs object web


【解决方案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

【讨论】:

  • 这不是因为setState是异步的,而是因为闭包一直在引用旧值。
【解决方案2】:

这是因为useEffect 处理程序在创建时设置的allParticipants 的值已关闭。因此,每当您引用 allParticipants 时,您都会得到相同的值 - 它永远不会通过 setter 更新。

【讨论】:

    猜你喜欢
    • 2015-12-04
    • 2018-08-19
    • 2020-11-28
    • 2013-02-10
    • 2019-03-22
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    • 2015-06-21
    相关资源
    最近更新 更多