访问 URL 参数的 ReactJS PrivateRoute

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

我有一个看起来像这样的 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 组件?

最佳答案

你可以这样写:

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

关于访问 URL 参数的 ReactJS PrivateRoute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49186183/

相关文章:

javascript - React Hook useEffect错误缺少依赖项

javascript - 这个导出是什么意思呢?这是一个执行两个函数的对象吗?

javascript - "withRouter"和 redux 的 "connect()"的问题

javascript - 浏览器后退按钮无法在 React Router v4 中导航

javascript - 使用带有 secret 的 github 操作对应用程序构建/部署进行 react

javascript - 如何从中心计算 map LatLngBounds 并手动缩放?

react-router - 从 React Router.browserHistory 获取以前的路径

reactjs - 什么是识别我当前使用 react-router 4 的路线的更好方法

reactjs - 使用 React Hooks 进行依赖注入(inject)

javascript - 如何正确使用react-router