P粉3739908572023-08-27 11:27:14
我认为你可能想在提交表单时使用findCountry
作为路由动作。加载器在第一次加载路由时运行。稍后可以调度一个动作。
基本示例:
const router = createBrowserRouter([ { index: true, element: <CountriesList />, loader: countriesLoader, action: findCountry } ]); <RouterProvider router={router} />
const countriesLoader = async () => {
const res = await fetch("https://restcountries.com/v3.1/all/");
if (!res.ok) {
throw Error("无法获取数据!");
}
return res.json();
};
const findCountry = async ({ request }) => {
const formData = await request.formData();
const res = await fetch(
`https://restcountries.com/v3.1/name/${formData.get("country")}`
);
if (!res.ok) {
throw Error("无法获取数据!");
}
return res.json();
};
import { Form, useActionData, useLoaderData } from "react-router-dom"; const CountriesList = () => { const searchResult = useActionData(); const countriesData = useLoaderData(); return ( <> ... <Form method="post" replace> <label> 搜索 <input required type="text" name="country" /> </label> <button type="submit">创建</button> </Form> ... </> ); };