javascript - 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块中的赋值。这是某种异步的东西吗?
解决方案
<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
你可以在网上找到很多关于这个主题的东西
推荐阅读
- javascript - 如何使用 2 个道具进行数学运算?
- python - How to make a list of the summed digits, in another list in Python?
- django - 如何在 django 中正确获取 webpack js 文件?
- r - Scrape and Loop with Rvest
- ios - 为测试人员归档时,如何将 .entitlements 中的“APS 环境”值设置为“开发”?
- android - 浏览文件夹并上传文件 firebase
- javascript - Nodejs require()(require()) to import
- ruby-on-rails - CLI 'Rails s' 命令不起作用,localhost 拒绝连接
- python - 为什么 fiona 在导入 geopandas 时会出错?
- java - 循环链表链接后到前,没有前参考