reactjs – 如何在React Router中的多个私有页面上呈现这些组件?

使用React Router 4,构建我们的Web应用程序.

情况如下:我有五页:“主页”,“日程安排”,“个人资料”,“小组”和“活动”.

任何人都可以访问主页,其他四个需要登录.

我想要做的是渲染一个将显示在这四个页面上的导航,但不显示在主页上.

这是我到目前为止在路由器中的内容.

const renderMergedProps = (component, ...rest) => {
  const finalProps = Object.assign({}, ...rest);
  return React.createElement(component, finalProps);
};

const PropsRoute = ({ component, ...rest }) => {
  return (
    <Route
      {...rest}
      render={routeProps => {
        return renderMergedProps(component, routeProps, rest);
      }}
    />
  );
};

const PrivateRoute = ({ component, isLoggedIn, ...rest }) => (
  <Route
    {...rest}
    render={routeProps => {
      //I'm currently forcing open the login with "true" just for testing

//这将是最终的(isLoggedIn?).
          return(true || isLoggedIn)? (
            renderMergedProps(component,routeProps,rest)
          ):(
            
          );
        }}
      />
    );

const RouterComponent = props => (
  <BrowserRouter>
    <div>
      <Route exact path="/" component={HomePage} />
      <Switch>
        <PrivateRoute
          isLoggedIn={props.isLoggedIn}
          path="/my-profile"
          component={MyProfile}
          title="My Profile"
        />
        <PrivateRoute
          isLoggedIn={props.isLoggedIn}
          path="/my-schedule"
          component={MySchedule}
          title="My Schedule"
        />
        <PrivateRoute
          isLoggedIn={props.isLoggedIn}
          path="/my-groups"
          component={MyGroups}
          title="My Groups"
        />
        <PrivateRoute
          isLoggedIn={props.isLoggedIn}
          path="/my-events"
          component={MyEvents}
          title="My Events"
        />
      </Switch>
    </div>
  </BrowserRouter>
);

const mapStateToProps = state => ({ 
  isLoggedIn: state.auth.status === "authorized"
});

export default connect(mapStateToProps)(RouterComponent);

最佳答案 您应该能够将您的{Homepage}路由包裹在交换机内,并确保路由是准确的,然后将PrivateRoutes放在交换机外但在Div内部.在您的私人路线之前但在开关关闭之后,有一条“/”(不完全匹配)的路线,用于渲染导航栏.

按照这种逻辑,主页将在“/”处独自呈现(在交换机内部).如果你点击私人路线,因为你在一个开关之外,它们将包含渲染,因此它将在NavBar上匹配(不完全匹配),然后匹配您所在的私人路线.

点赞