Gus*_*ias 5 javascript reactjs react-hooks react-query
我一直在尝试学习 React-query 但似乎无法用我的onSubmit事件触发请求。现在,代码正在发送以“washington”作为默认参数的请求并将其打印到屏幕上,并且新请求也会随事件触发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;
Run Code Online (Sandbox Code Playgroud)
也可以setCity在onSubmit表单的事件中调用,因为该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>
Run Code Online (Sandbox Code Playgroud)
确保为您的输入提供 a name,以便您可以从表单提交事件中获取它。
您可以使用useMutation 挂钩。正如文档所说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 会自动重新获取数据。
| 归档时间: |
|
| 查看次数: |
8721 次 |
| 最近记录: |