首页 > 解决方案 > React 条件渲染不显示任何内容

问题描述

使用react-router-dom: 4.3.1反应应用程序:

主 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>
        );
    }

我在使用此代码时看到白屏,但是当我分配给第一个或第二个Switch路由时,如果它在这两种情况下都能正常工作。

我猜这个问题来自if块中的赋值。这是某种异步的东西吗?

标签: javascriptreactjsreact-router

解决方案


<Switch />无论场景如何,您都可能希望在组件内部设置路由,并拥有公共私有路由组件。这是一种常见的方法:

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(function) 和isAuthenticated(boolean) 作为 props,我们将其余的 props 向下传递 ( {...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

你可以在网上找到很多关于这个主题的东西


推荐阅读