反应路由器|私有路由器上的呼叫功能

时间:2018-04-27 13:36:04

标签: reactjs react-router-v4

我正在使用React Router。我必须在private router

上调用函数

路线

<Router history={history}>
        <div>
          <Spin spinning={this.props.isloading}>
            <Switch>>
              <Route path="/login" component={Login} />
              <PrivateRoute path="/Dashboard" component={Dashboard} />
              <Route path='*' component={NotFound} />
            </Switch>
          </Spin>
        </div>
      </Router>

PrivateRoute

export const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
            this.validateSession()
            ? <Component {...props} />
            : <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
    )} />
)

我可以调用函数this.validateSession()吗?它显示类型错误。

2 个答案:

答案 0 :(得分:0)

您需要传递验证功能

public boolean remove(Client e)

答案 1 :(得分:0)

您应该将validate作为prop传递给PrivateRoute组件

<PrivateRoute path="/Dashboard" validate={this.validateSession} component={Dashboard} />

,您的组件将如下所示:

export const PrivateRoute = ({ component: Component, validate, ...rest }) => (
    <Route {...rest} render={props => (
            validate()
            ? <Component {...props} />
            : <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
    )} />
)