我在reactjs应用程序中使用受保护的路由,我想知道如何在受保护的路由中传递道具,或者是否有更优雅的方法来解决我的问题。
我觉得需要在受保护的路由中传递道具的原因是注销按钮位于受保护的组件中,我需要与父组件通信,其中包含用户正在尝试的所有路由退出。
以下是相关代码:
父组件:
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>
)};
不幸的是,我不知道如何解决这个问题。
在路径组件中传递道具是否被视为不良做法?如果是这样,我怎么办?如果没有,我该如何正确地通过道具?
答案 0 :(得分:1)
在课堂外声明你的PrivateRoute
:
const PrivateRoute = ({ component: Component, handleLogout, isAuthenticated, ...rest }) => (
<Route {...rest} render={(props) => (
isAuthenticated === true
? <Component {...props} handleLogout={handleLogout} />
: <Redirect to="/Login"/>
)} />
);
然后将handleLogout
传递给您的PrivateRoute
道具:
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
如下所示,以便通过传播所有道具将任何道具传递给组件:
const PrivateRoute = ({ component: Component, isAuthenticated, ...rest }) => (
<Route {...rest} render={(props) => (
isAuthenticated === true
? <Component {...props} {...rest} />
: <Redirect to="/Login"/>
)} />
);
答案 1 :(得分:1)
为PrivateRoute
HOC
render() {
const PrivateRoute = ({ component: Component, handleLogout, ...rest }) => (
<Route {...rest} render={(props) => (
isAuthenticated === true
? <Component handleLogout={handleLogout} {...props} />
: <Redirect to="/Login"/>
)} />
);
return (
<HashRouter basename={BASE_URL}>
<PrivateRoute
exact
path={'/login'}
component={Login}
handleLogout={this.handleLogout}
/>
<PrivateRoute
exact
path={'/Main/'}
component={Main}
handleLogout={this.handleLogout}
/>
</HashRouter>
);
}
答案 2 :(得分:1)
这是一种更通用的解决方案,可以根据需要将尽可能多的道具传递给组件:
render() {
const PrivateRoute = ({ component: Component, data, ...rest }) => (
<Route {...rest} render={(props) => (
isAuthenticated === true
? <Component {...props} {...data} />
: <Redirect to="/Login"/>
)} />
);
return (
<HashRouter basename={BASE_URL}>
<PrivateRoute
exact
path={'/login'}
component={Login}
data={{
handleLogout=this.handleLogout,
...
someProp=this.prop
}}
/>
<PrivateRoute
exact
path={'/Main/'}
component={Main}
data={{
handleLogout=this.handleLogout,
...
someProp=this.prop
}}
/>
</HashRouter>
);
}