[英]react-router v6 wrapped route component not working
如何渲染组合的Route
组件
上面例子的底线是,在下面的代码中, Wrapped
路由永远不会渲染它的元素
const App = () => (
<Routes>
<Wrapped/>
<Route path="/inline" element={<span >Inline works</span>} />
</Routes>
);
const Wrapped = () => <Route path="/wrapped" element={<span>wrapped</span>} />
有没有办法用带有 react-router v6 的Route
组件进行这种组合? 还是 react-router v6 只支持直接嵌套在Routes
组件中的Route
?
编辑,更具体地说,我试图获得使用ProtectedRoute
组件的建议,其中包括:
type Props = {
element: ReactElement;
redirectRoute: string;
} & RouteProps;
const ProtectedRoute = ({element, redirectRoute, ...rest}: Props) => {
const {isAuthenticated} = useAuth();
<Route {...rest} element={isAuthenticated() ? element : <Navigate to={redirectRoute}/>}/>
}
编辑:这似乎曾经在旧的测试版中工作,所以这可能是一个错误。 目前最新版本是 6.0.0-beta.4 & 我记录了一个问题: https : //github.com/remix-run/react-router/issues/8066
在您的代码中,您尝试使用 Wrapped Component 作为路由器,但事实并非如此。 它是一个返回 React Router 元素的 React 元素。 由于在这个简单的用例中您只需要 Router ,您可以将 is 视为一个函数:
<Suspense fallback={null}>
<Routes>
{/* Use this as a normal function, and also function name etc.,*/}
{Wrapped()}
<Route path="/inline" element={<span>Inline works</span>} />
</Routes>
</Suspense>
但是,我建议不要通过尝试在路由上添加自定义来使路由复杂化,而是将要路由的组件包装起来。
例如,
const Wrapped = () => <Route path="/wrapped" element={<span>wrapped</span>} />;
到
<Route path="/wrapped" element={<Wrapped>wrapped component</Wrapped>} />
还是 react-router v6 只支持直接嵌套在 Routes 组件中的 Route?
正确,RRv6 不支持路由组合。 相反,请尝试在element
道具中使用<Wrapped />
组件。 例如
<Route path="/foo" element={<Wrapped>/* something here */</Wrapped>} />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.