如何将 UseQuery 与 useEffect 结合使用?
How to use UseQuery with useEffect?
如何在React.UseEffect中使用UseQuery?这是我的简单查询
const {allrecord} = useQuery(ME, {
onCompleted: ({ meTeacher}) => {
setUser(meIAM);
getRecords({
variables: {
orgId: meIAM.organization.id,
pagingArg: {},
},
}).then(({ data }) => displayRecord(data.record));
},
});
useEffect(() => {
console.log(allLocations)
}, []);
useQuery
是一个钩子,因此不能在分支下使用。
这意味着您必须在您的组件内部而不是在分支语句(if/else/switch/useEffect)下调用useQuery
。
如果您需要对 useQuery
的结果执行某些操作,只需使用依赖于该结果的 useEffect
Apollo Client useQuery
钩子在组件渲染时自动执行相应的查询。这使得它非常类似于在 useEffect
中执行没有依赖关系的查询。喜欢:
useEffect(() => {
const data = executeQuery()
}, [])
还有一个替代挂钩,useLazyQuery
可用于执行查询以响应某些事件,例如按下按钮。
这里回答得很好https://github.com/trojanowski/react-apollo-hooks/issues/158
const { loading, data, error } = useQuery(SOME_QUERY)
// If you absolutely need to cache the mutated data you can do the below. But
// most of the time you won't need to use useMemo at all.
const cachedMutatedData = useMemo(() => {
if (loading || error) return null
// mutate data here
return data
}, [loading, error, data])
if (loading) return <Loader />
if (error) return <Error />
// safe to assume data now exist and you can use data.
const mutatedData = (() => {
// if you want to mutate the data for some reason
return data
})()
return <YourComponent data={mutatedData} />
如何在React.UseEffect中使用UseQuery?这是我的简单查询
const {allrecord} = useQuery(ME, {
onCompleted: ({ meTeacher}) => {
setUser(meIAM);
getRecords({
variables: {
orgId: meIAM.organization.id,
pagingArg: {},
},
}).then(({ data }) => displayRecord(data.record));
},
});
useEffect(() => {
console.log(allLocations)
}, []);
useQuery
是一个钩子,因此不能在分支下使用。
这意味着您必须在您的组件内部而不是在分支语句(if/else/switch/useEffect)下调用useQuery
。
如果您需要对 useQuery
的结果执行某些操作,只需使用依赖于该结果的 useEffect
Apollo Client useQuery
钩子在组件渲染时自动执行相应的查询。这使得它非常类似于在 useEffect
中执行没有依赖关系的查询。喜欢:
useEffect(() => {
const data = executeQuery()
}, [])
还有一个替代挂钩,useLazyQuery
可用于执行查询以响应某些事件,例如按下按钮。
这里回答得很好https://github.com/trojanowski/react-apollo-hooks/issues/158
const { loading, data, error } = useQuery(SOME_QUERY)
// If you absolutely need to cache the mutated data you can do the below. But
// most of the time you won't need to use useMemo at all.
const cachedMutatedData = useMemo(() => {
if (loading || error) return null
// mutate data here
return data
}, [loading, error, data])
if (loading) return <Loader />
if (error) return <Error />
// safe to assume data now exist and you can use data.
const mutatedData = (() => {
// if you want to mutate the data for some reason
return data
})()
return <YourComponent data={mutatedData} />