【问题标题】:Custom hook inside useStateuseState 中的自定义钩子
【发布时间】:2020-11-23 05:39:34
【问题描述】:

我有一个用于重用 UseEffect 的自定义钩子

import {useState, useEffect } from 'react'

export default function useGetList(getListFunc) {

    const [currentList, setCurrentList] = useState([]);

    useEffect(() => {
        async function fetchData() {
            setCurrentList(await getListFunc())
        }
        fetchData();    
    }, [getListFunc]);

    
    return currentList
}

我可以直接在组件中使用这个自定义钩子。

 const currentStaff1 = useGetList(getStaffListFunc)
 console.log(currentStaff1)

但是用它来设置状态变量的默认值是给一个空数组[]

const [currentStaff, setCurrentStaff] = useState(useGetList(getStaffListFunc))
console.log(currentStaff)

这里有什么问题?

【问题讨论】:

  • 对不起,如果这是一个明显的调试并且您已经检查过它,但是您是否尝试通过调用 useEffect 来测试渲染循环中的内容,例如:useEffect(() => console.log(currentStaff), [currentStaff]),以防万一console.log(currentStaff) 你现在在 currentStaff 更新之前被调用?我今天早些时候在 userLogin 上遇到了类似的问题,所以我问是因为它在我的大脑前面。
  • useEffect 类似于 componentDidMount 和 componentDidUpdate。当组件被挂载/更新并且您在自定义挂钩中进行异步调用时,它将运行。它不会等到承诺得到解决。尝试使用自定义钩子依赖在 useEeffect 中设置状态
  • 你不应该在 useState 中调用 useState。太疯狂了
  • @JMadelaine 。我现在看到了疯狂。

标签: reactjs react-hooks


【解决方案1】:

你可以试试这个

const [currentList, setCurrentList] = useState([]);

useEffect(() => {
    async function fetchData() {
        setCurrentList(await getListFunc())
    }
    fetchData();    
}, [getListFunc]);


return [currentList] // return as array

然后在你的组件中

const [currentStaff] = useGetList(getStaffListFunc)

【讨论】:

    【解决方案2】:

    在意识到在另一个 statehook 中使用了 state hook 之后,我将 useEffect 直接移到了组件中,而不是可重用的自定义 hook。

    【讨论】:

      猜你喜欢
      • 2020-12-05
      • 2020-02-19
      • 1970-01-01
      • 2021-05-10
      • 2013-05-01
      • 2021-02-14
      • 1970-01-01
      • 2017-05-22
      • 2020-08-20
      相关资源
      最近更新 更多