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> ... </> ); };