到目前为止,我还是个反应查询的新手,非常喜欢它。我知道它主要是一个UI库。因此,它非常适合处理/显示错误、加载状态。但我经常发现自己想以异步的方式等待一些特定的操作。所以,我希望能够在触发一个动作(例如重定向(之前等待一个承诺的返回。
这里有一个例子:
const NewPostForm = props => {
const history = useHistory();
const mutatePostInfo = useUpdatePost(); // useMutate hook
const [value, setValue] = useState("")
const handleSubmit = () => {
mutatePostInfo.mutate(value);
// I WANT TO: wait for the action to complete before redirecting
history.push("/new-route/")
}
return (
<form onSubmit={handleSubmit}>
<input value={value} onChange={(e) => setValue(e.target.value)} />
</form>
)
}
useMutation
返回的mutate
函数将options作为第二个参数,当突变成功时,您可以使用onSuccess
选项执行某些操作:
mutatePostInfo.mutate(
value,
{
onSuccess: () => history.push("/new-route/")
}
);
还有onError
(用于错误(和onSettled
回调(如果您想在成功或错误的情况下重定向(。
- 突变异步
useMutation
附带一个名为mutateAsync
的内置函数,您可以用await
调用它。阅读此处了解更多信息。
const NewPostForm = props => {
const history = useHistory();
const mutatePostInfo = useUpdatePost(); // useMutate hook
const [value, setValue] = useState("")
const handleSubmit = async () => {
await mutatePostInfo.mutateAsync(value); // waits for the action to complete before redirecting
history.push("/new-route/")
}
return (
<form onSubmit={handleSubmit}>
<input value={value} onChange={(e) => setValue(e.target.value)} />
</form>
)
}
mutate
和onSuccess
useMutation
附带了另一个名为mutate
的函数。mutate
的第二个参数是一个覆盖传递给useMutation
的选项的选项。当突变成功时,该函数将启动,并将传递给突变的结果。查看此处了解更多信息。
const NewPostForm = props => {
const history = useHistory();
const mutatePostInfo = useUpdatePost(); // useMutate hook
const [value, setValue] = useState("")
const handleSubmit = () => {
mutatePostInfo.mutate( value, { onSuccess: () => history.push("/new-route/") });
}
return (
<form onSubmit={handleSubmit}>
<input value={value} onChange={(e) => setValue(e.target.value)} />
</form>
)
}
如果要等待其他没有onSuccess函数的值或函数完成,则可以使用依赖查询来停止查询,直到该值存在/符合您的条件。
https://egghead.io/lessons/react-use-dependent-queries-to-delay-react-query-s-usequery-from-firing-on-render
const [payload, setPayload] = useState();
const someFunc = () => setPayload("data");
const { data } = useQuery(payload && ["queryKey", { payload }],
queryName
);
someFunc();
将等待直到有效载荷具有值(在这种情况下为"0"(;数据";,在它发送queryName请求之前,您还可以传入一个具有返回值的函数,该函数将等待该返回值。
您可以使用依赖查询。例如:
// Get the user
const { data: user } = useQuery(['user', email], getUserByEmail)
const userId = user?.id
const { isIdle, data: projects } = useQuery(
['projects', userId],
getProjectsByUser,
{
// The query will not execute until the userId exists
enabled: !!userId,
}
)
// isIdle will be `true` until `enabled` is true and the query begins to fetch.
// It will then go to the `isLoading` stage and hopefully the `isSuccess` stage :)