Javascript React条件渲染不';我什么也没表现出来
React应用程序与React路由器dom:4.3.1 主App.js呈现:Javascript React条件渲染不';我什么也没表现出来,javascript,reactjs,react-router,Javascript,Reactjs,React Router,React应用程序与React路由器dom:4.3.1 主App.js呈现: render() { let routes = ( <Switch> <Route component={LogIn} path="/login" /> <Redirect to="/login" /> </Switch> );
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>
);
}
render(){
让路线=(
);
如果(此.props.isAuthenticated){
路线=(
);
}
返回(
{routes}
);
}
当使用此代码时,我会看到白色屏幕,但当我分配给路由第一个或第二个开关时,它在这两种情况下是否都能正常工作
我猜问题来自if块中的赋值。这是某种异步的东西吗?您可能希望在
组件内部设置路由,无论在何种情况下,都可以使用公共或私有路由组件。以下是一种常见的方法:
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" />
)
)}
/>
);
更多信息请访问Tyler McGinnis的网站:
关于这一主题的另一篇文章:
你可以在网上找到很多关于这个主题的东西看起来不错。请使用演示问题的工具更新您的问题,最好是使用堆栈片段(
[]
工具栏按钮)运行的工具。堆栈代码段支持React,包括JSX。(使用if
/else
可能更有意义,而不是总是创建第一个集合,有时只是用第二个集合替换它,但它应该按原样工作…)@T.J.Crowder我发现分配后,react路由器无法识别路由组件中提供的路径,并且总是重定向。我恐怕不知道您的意思,以及它是否与我上面的评论或问题本身有关。。。?
...your code
render() {
<Switch>
<PublicRoute path="/" component={YourPublicComponent} />
<PrivateRoute path="/" isAuthenticated component={ParcelListView} />
</Switch>
}