访问URL参数的ReactJS PrivateRoute

时间:2018-03-09 03:33:00

标签: reactjs react-router react-router-v4 url-parameters react-router-dom

我有一个看起来像这样的React Route ...它根据URL参数的值有条件地呈现Component:

<Route path="/blog/:postId" render={(props) = {
    const postId = props.match.params.postId; // extract post from url
    return (
        post
        ? <Post {...props} postId={postId} />
        : <div>Post does not exist</div>
    );
}

我希望只有经过身份验证的用户才能访问此路由,这意味着我会将其转换为这样的PrivateRoute(from the docs):

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      fakeAuth.isAuthenticated ? (
        <Component {...props} />
      ) : (
        <Redirect
          to={{
            pathname: "/login",
            state: { from: props.location }
          }}
        />
      )
    }
  />
);

然后我会像这样使用私人路线...

<PrivateRoute path="/blog/:postId" component={Post} />

但是,如何检查PrivateRoute中的URL参数并根据URL参数有条件地呈现Post组件?

1 个答案:

答案 0 :(得分:0)

你可以这样写:

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={props => {
      const postId = props.match.params.postId;
      return fakeAuth.isAuthenticated ? (
        postId ?
          <Component {...props} />
          : <div>Post does not exist</div>
      ) : (
        <Redirect
          to={{
            pathname: "/login",
            state: { from: props.location }
          }}
        />
      )
    }}
  />
);

但这不是一个好主意,因为如果将来你又想要一个条件,那么PrivateRoute会变得更加复杂。我建议在Post组件中加入所有类型的检查,如下所示:

render(){
   if(!this.props.match.params.id)
     return <div>Post does not exist</div>
   else (.....)
}

或者,如果您不想更改Post组件,请创建一个包装器组件并将此逻辑放在其中,如下所示:

<PrivateRoute path="/blog/:postId" component={PostWrapper} />

const PostWrapper = props => {
   if(props.match.params.id)
      return <Post {...props} />
   return <div>Post does not exist</div>
}