【问题标题】:React Conditional rendering doesn't show anythingReact 条件渲染不显示任何内容
【发布时间】:2018-11-05 10:35:37
【问题描述】:

使用 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 的情况下分配给 routes 第一个或第二个 Switch 时,它在两者中都能完美运行案例。

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

【问题讨论】:

  • 看起来不错。请使用 minimal reproducible example 来更新您的问题,以展示问题,最好是使用 Stack Snippets([&lt;&gt;] 工具栏按钮)的 runnable 问题。 Stack Snippets 支持 React,包括 JSX; here's how to do one.
  • (使用if/else 会更有意义,而不是总是创建第一个集合只是为了有时用第二个替换它,但它应该工作原样...)
  • @T.J.Crowder 我发现分配后反应路由器无法识别 Route 组件中提供的路径并且总是重定向
  • 恐怕我不知道你的意思是什么,这是否与我上面的 cmets 或问题本身有关......?

标签: javascript reactjs react-router


【解决方案1】:

您可能希望在 &lt;Switch /&gt; 组件内设置路由,无论场景如何,并且具有 publicprivate 路由组件。这是一种常见的方法:

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

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

【讨论】:

    猜你喜欢
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-30
    • 2022-01-21
    • 1970-01-01
    • 2019-11-30
    • 2011-12-22
    相关资源
    最近更新 更多