【发布时间】: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