[英]React Conditional rendering doesn't show anything
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
(函數)和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
您將可以在網絡上找到很多關於該主題的內容
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.