【问题标题】:useEffect not setting react hooksuseEffect 未设置反应挂钩
【发布时间】:2020-08-29 21:55:21
【问题描述】:

我有一个看起来像这样的 useEffect 函数。

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

getColls() 函数设置 pageColl 变量。

//getColls()
    const getColls = () => {
        Service.getCollections()
        .then(data => 
            setPageColl(data.collections.find(coll => coll._id === userId))
        )
    }
//states
const [pageColl, setPageColl] = useState(null);

pageColl 应该设置为一个对象,但由于某种原因,当我尝试使用 console.log(pageColl) 时,我得到了一个 null。就好像 setPageColl 从未被调用过。我知道数据是在 getCols 中返回的,因为我可以在那里进行控制台记录。

【问题讨论】:

标签: reactjs react-hooks use-effect


【解决方案1】:

你不能在调用 getColls() 方法后立即检查“pageColl”状态,因为 api 调用是异步的。

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

你可以像上面那样检查

【讨论】:

    猜你喜欢
    • 2021-03-16
    • 2019-07-31
    • 1970-01-01
    • 2021-05-24
    • 2021-02-11
    • 2020-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多