在React Router中重写自定义路由以使用渲染道具而不是组件道具



我有一个使用React Router的React应用程序。我的代码中有一个错误,这是由于我的自定义ProtectedRoute组件中的某些内容造成的

const ProtectedRoute = ({ component, ...args }) => (
<Route
component={withAuthenticationRequired(component, {
onRedirecting: () => <Loading />,
})}
{...args}
/>
);
export default ProtectedRoute;

你可以在这里阅读我的另一篇文章,详细探讨我的问题:Auth0 ProtectedRoute组件阻止组件随状态而更改

但现在我只是试图重写这个函数,以使用render道具,而不是component道具(我认为这是导致问题的原因(。这是我尝试过的,但没有奏效:

const ProtectedRoute = ({component: ComponentToRender, path, rest}) => {
return <Route
{...rest}
path={path}
render={(props) => {
withAuthenticationRequired(() => (<ComponentToRender {...props}/>), {
onRedirecting: () => <Loading/>
})
}
}
/>
}

有人知道如何重写以使用render道具吗?

谢谢!

我认为您传递给render的箭头函数没有返回任何内容,因为您使用的是体括号,而不是return。阅读有关MDN 上箭头功能的更多信息

你可以这样做:

render={(props) => (
withAuthenticationRequired(() => (<ComponentToRender {...props}/>), {
onRedirecting: () => <Loading/>
})
)}

最新更新