React条件渲染不显示任何内容

时间:2018-11-05 10:35:37

标签: javascript reactjs react-router

具有 react-router-dom:4.3.1

React应用:

主要App.js渲染:

render() {
        let routes = (
            <Switch>
                <Route component={LogIn} path="/login" />
                <Redirect to="/login" />
            </Switch>
        );

        if (this.props.isAuthenticated) {
            routes = (
                <Switch>
                    <Route component={ParcelListView} path="/" exact />
                    <Route component={StatusTable} path="/status" />
                    <Redirect to="/" />
                </Switch>
            );
        }

        return (
            <div className="app">
                {routes}
            </div>
        );
    }

我看到白屏使用此代码,但是当我在没有 if 的情况下分配给路由的第一个或第二个 Switch 时,它在两种情况下均能正常工作案例。

我猜问题出在 if 块中。这是异步的东西吗?

1 个答案:

答案 0 :(得分:2)

无论哪种情况,您都可能希望在<Switch />组件内设置路由,并且具有 public private 路由组件。这是一种常见的方法:

const PublicRoute = ({
 isAuthenticated,
 component: Component,
 ...rest
}) => (
<Route
  {...rest}
  component={props => (
    isAuthenticated ? (
      <Redirect to="/somewhere" />
    ) : (
    <Component {...props} />
  ))}
 />
);

const PrivateRoute = ({
  isAuthenticated,
  component: Component,
  ...rest
}) => (
<Route
  {...rest}
  component={props => (
    isAuthenticated ? (
      <div>
        <Header />
        <Component {...props} />
      </div>
    ) : (
    <Redirect to="/login" />
  )
  )}
  />
);

两个组件都将component(函数)和isAuthenticated(布尔值)用作道具,无论如何我们将其余的道具向下传递({...rest})(path等)。 )

通过这种方式,您可以根据传递到组件的props来允许/拒绝路由:

...your code

render() {
 <Switch>
  <PublicRoute path="/" component={YourPublicComponent} />
  <PrivateRoute path="/" isAuthenticated component={ParcelListView} />
 </Switch>
}

Tyler McGinnis网站的更多信息:https://tylermcginnis.com/react-router-protected-routes-authentication/ 关于该主题的另一篇文章:https://medium.com/@tomlarge/private-routes-with-react-router-dom-28e9f40c7146

您将能够在网络上找到很多关于该主题的东西