在调用自定义Datafetch挂钩后,如何使用useReducer分配初始状态?我不断得到空值

问题描述 投票:0回答:1

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

我称之为自定义挂钩的组件。

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)时,我得到空值。

我的自定义数据获取挂钩

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 hook
1个回答
0
投票

问题是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]);
© www.soinside.com 2019 - 2024. All rights reserved.