我可以用下面的方式在路由器上使用Redux吗?还有,有没有理由用这种方式而不是使用路由器模块的钩子?
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import HomePage from "./pages/HomePage";
import RootLayout from "./components/RootLayout";
import SearchPage from "./pages/SearchPage";
import WeatherPage from "./pages/WeatherPage";
import SettingsPage from "./pages/SettingsPage";
import { loader as HomePageLoader } from "./pages/HomePage";
import { useDispatch, useEffect } from "react-redux";
let router = "";
function App() {
const dispatch = useDispatch();
useEffect(() => {
router = createBrowserRouter([
{
path: "/",
element: <RootLayout />,
children: [
{
index: true,
element: <HomePage />,
loader: () => {
HomePageLoader(dispatch);
}
},
{ path: "search", element: <SearchPage /> },
{ path: "weather", element: <WeatherPage /> },
{ path: "settings", element: <SettingsPage /> }
]
}
]);
}, []);
return (
<RouterProvider router={router}>
</RouterProvider>
);
}
export default App;
字符串
1条答案
按热度按时间2ul0zpep1#
当然。但是,与其使用
useEffect
钩子来改变一个局部“全局”router
变量,不如使用useMemo
钩子来记忆router
,并在作用域中关闭dispatch
函数。另外,
useEffect
不是react-redux
导出。范例:
字符串
确保
homePageLoader
是一个curried函数,以便可以将dispatch
函数传递给它,并返回一个传递给加载器属性的函数。范例:
型