Reactjs 调用自定义Datafetch钩子后,如何使用useReducer分配初始状态?我一直在变空
我创建了一个自定义datafetch钩子,但当我使用reducer函数将其设置为初始状态时,它会显示为null 我调用自定义钩子的组件Reactjs 调用自定义Datafetch钩子后,如何使用useReducer分配初始状态?我一直在变空,reactjs,react-hooks,Reactjs,React Hooks,我创建了一个自定义datafetch钩子,但当我使用reducer函数将其设置为初始状态时,它会显示为null 我调用自定义钩子的组件 const collection = 'items' const whereClause = { array: "lists", compare: 'array-contains', value: 'Pantry' } const res = useDataFetchWhere(collection, whereClause) const data = res.
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 }
}
有什么我需要做或打电话的方式不同吗
谢谢。问题在于,
useDataFetchWhere
不会立即返回数据获取的结果,而只是在请求完成一段时间后,然后setResponse
才会设置实际数据。因此,您不能将响应设置为useReducer
调用的初始状态
在使用请求的结果之前,需要等待请求完成。您可以为减速机创建一个操作(例如,SET_DATA
),在减速机到达后设置结果
您已经有可用的isLoading
标志:
const [state, dispatch] = useReducer(reducer, null);
useEffect(() => {
if (!isLoading) {
const data = res.response;
dispatch({type: 'SET_DATA', data});
}
}, [isLoading]);
谢谢我试着在没有useEffect的情况下使用if函数,它就像一个无限循环。效果很好。