在受保护的路线reactjs中传递道具

A.S*_*S.J 3 javascript reactjs react-router

我在我的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>
)};
Run Code Online (Sandbox Code Playgroud)

不幸的是,我不知道该如何解决这个问题。

在路线组件中传递道具是否被认为是不好的做法?如果是这样,我还能如何处理?如果没有,我如何正确通过道具?

Dyo*_*Dyo 5

PrivateRoute在课堂上宣告您的情况:

const PrivateRoute = ({ component: Component, handleLogout, isAuthenticated, ...rest }) => (
        <Route {...rest} render={(props) => (
            isAuthenticated === true
            ? <Component {...props} handleLogout={handleLogout} />
            : <Redirect to="/Login"/>
        )} />
);
Run Code Online (Sandbox Code Playgroud)

然后传递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>
    )
};
Run Code Online (Sandbox Code Playgroud)

您可能想在PrivateRoute下面声明自己,以便通过传播所有prop来将任何prop传递给组件:

const PrivateRoute = ({ component: Component, isAuthenticated, ...rest }) => (
        <Route {...rest} render={(props) => (
            isAuthenticated === true
            ? <Component {...props} {...rest} />
            : <Redirect to="/Login"/>
        )} />
);
Run Code Online (Sandbox Code Playgroud)