我在我的reactjs应用程序中使用受保护的路由,我想知道如何在受保护的路由中传递道具,或者是否有更优雅的方法来解决我的问题。
我觉得需要在受保护的路由中传递 props 的原因是注销按钮位于受保护的组件内,我需要与包含用户尝试注销的所有路由的父组件进行通信。
这是相关代码:
父组件:
render() {
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={(props) => (
isAuthenticated === true
? <Component {...props} /*I tried inserting handleLogout={this.handleLogout} here */ />
: <Redirect to="/Login"/>
)} />
)
return (
<HashRouter basename={BASE_URL}>
<div className="stories-module">
<PrivateRoute
exact
path={'/login'}
component={Login}
/>
<PrivateRoute
exact
path={'/Main/'}
component={Main}
/>
</HashRouter>
)};
不幸的是,我不知道还能如何解决这个问题。
在路由组件中传递 props 被认为是不好的做法吗?如果是这样,我还能如何处理这个问题,如果不是,我该如何正确传递道具?
声明你的PrivateRoute
课外:
const PrivateRoute = ({ component: Component, handleLogout, isAuthenticated, ...rest }) => (
<Route {...rest} render={(props) => (
isAuthenticated === true
? <Component {...props} handleLogout={handleLogout} />
: <Redirect to="/Login"/>
)} />
);
然后通过handleLogout
给你的PrivateRoute
props :
render() {
return (
<HashRouter basename={BASE_URL}>
<div className="stories-module">
<Route
exact
path={'/login'}
component={Login}
/>
<PrivateRoute
exact
path={'/Main/'}
component={Main}
handleLogout={this.handleLogout}
isAuthenticated={isAuthenticated}
/>
</div>
</HashRouter>
)
};
你可能想声明你PrivateRoute
如下所示,以便通过传播所有 props 将任何 props 传递给组件:
const PrivateRoute = ({ component: Component, isAuthenticated, ...rest }) => (
<Route {...rest} render={(props) => (
isAuthenticated === true
? <Component {...props} {...rest} />
: <Redirect to="/Login"/>
)} />
);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)