我一直在尝试学习React-query,但似乎不能用我的onSubmit
事件触发请求。现在,代码正在发送以“华盛顿”作为默认参数的请求,并将其打印到屏幕上,并且还会通过onBlur
事件触发一个新的请求,并在键入的城市有效的情况下获取数据。
问题是,我希望我可以将此逻辑转移到submit()
函数,处理输入上的数据,并且只有当数据有效时,才继续发出请求。这就是我用一个免费的apiKey重现问题的stackblitz:StackBlitz
代码如下:
import React, { useState } from 'react';
import { useQuery } from 'react-query';
import axios from 'axios';
const Fetch = async city => {
let apiKey = '91b5ff77e9e7d1985a6c80bbbb3b2034';
const { data } = await axios.get(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`
);
return data;
};
const Weather = () => {
const [city, setCity] = useState('washington');
const { data, error } = useQuery(['temperature', city], () => Fetch(city));
const submit = () => {};
return (
<div>
<form onSubmit={submit}>
<input onBlur={e => setCity(e.target.value)} type="text" />
<button type="submit">send</button>
</form>
{!data ? null : <div>{data.main.temp}</div>}
</div>
);
};
export default Weather;
发布于 2021-07-05 19:47:08
您可以使用useMutation hooks。正如文档中所说的,mutations are typically used to create/update/delete data or perform server side-effects. For this purpose, React Query exports a useMutation hook.
。这个钩子将返回一个对象,该对象为您提供了一个突变函数,您可以使用该函数来根据用户交互触发请求。
const { mutate: renamedMutationFunction } = useMutation(newTodo => axios.post('/todos', newTodo))
。
然后,您可以在代码中的某个位置执行以下操作:
const handleClick = () => { renamedMutationFunction(); //invoking the mutation }
编辑
有关更好的解决方案,请参阅@TkDodo答案。基本上,您只需重新设置城市,react-query就会自动获取数据。
发布于 2021-07-11 15:43:35
您还可以在表单的onSubmit
事件中调用setCity
,因为onSubmit
事件在submit事件中获取完整的已提交表单:
<form
onSubmit={(event) => {
event.preventDefault();
const city = new FormData(event.currentTarget).get("city");
// do validation here
if (isValid(city)) {
setCity(city)
}
>
<input name="city" type="text" />
<button type="submit">send</button>
</form>
确保为您的输入提供一个name
,以便您可以从表单提交事件中获取它。
https://stackoverflow.com/questions/68261332
复制