【问题标题】:How can i use useReducer to assign initial state after calling custom Datafetch hook? I keep getting null调用自定义 Datafetch 挂钩后,如何使用 useReducer 分配初始状态?我一直为空
【发布时间】:2020-04-20 06:10:33
【问题描述】:

我创建了一个自定义数据获取挂钩,但是当我使用 reducer 函数将其设置为初始状态时,它显示为 null。

我调用自定义 Hook 的组件。

const collection = 'items'
const whereClause = { array: "lists", compare: 'array-contains', value: 'Pantry' }
const res = useDataFetchWhere(collection, whereClause)
const data = res.response
const [state, dispatch] = useReducer(reducer, data)

当我 console.log(state) 我得到 null。

我的自定义数据获取钩子

const useDataFetchWhere = (collection, whereClause) => {

    const [response, setResponse] = useState(null)
    const [error, setError] = useState(null)
    const [isLoading, setIsLoading] = useState(false)


    useEffect(() => {
        const fetchData = async () => {
            setIsLoading(true)
            setError(false)
            try {
                await db.collection(collection).where(whereClause.array, whereClause.compare, whereClause.value).get()
                    .then(data => {
                        setResponse(data.docs.map(doc => ({ ...doc.data(), id: doc.id })))
                        setIsLoading(false)
                        console.log('hello where')
                    })

            } catch (error) {
                setError(error)
            }
        }
        fetchData()
        return function cleanup() {
            console.log('cleaned up check')
        };
    }, [])

    return { response, error, isLoading }
}

有什么我需要做的或以不同的方式打电话的吗?

谢谢。

【问题讨论】:

    标签: reactjs react-hooks


    【解决方案1】:

    问题是useDataFetchWhere 不会立即返回数据获取的结果,而是在请求完成后一段时间,然后setResponse 将设置实际数据。因此,您不能将响应设置为 useReducer 调用的初始状态。

    您需要等到请求完成后再使用它的结果。您可以为 reducer 创建一个操作(例如SET_DATA),以便在结果出现后设置结果。

    您已经拥有可用的isLoading 标志:

    const [state, dispatch] = useReducer(reducer, null);
    
    useEffect(() => {
      if (!isLoading) {
        const data = res.response;
        dispatch({type: 'SET_DATA', data});
      }
    }, [isLoading]);
    

    【讨论】:

    • 谢谢!我试图在没有 useEffect 的情况下执行 if 函数,它进入了一个无限循环。效果很好。
    猜你喜欢
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 2020-01-23
    • 2021-12-07
    相关资源
    最近更新 更多