【问题标题】:ReactJS PrivateRoute that accesses URL parameter访问 URL 参数的 ReactJS PrivateRoute
【发布时间】:2018-08-17 13:52:21
【问题描述】:

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

<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 组件?

【问题讨论】:

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


    【解决方案1】:

    你可以这样写:

    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>
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-25
      • 1970-01-01
      • 1970-01-01
      • 2013-08-12
      • 1970-01-01
      • 2020-06-01
      • 1970-01-01
      • 2021-01-11
      相关资源
      最近更新 更多