![](/img/trans.png)
[英]how to redirect to another page when a certain condition is true using javascript
[英]How to redirect to some page if condition is true using react?
如果 isAdmin 為真,我想重定向到頁面“/items”。
下面是我的代碼,
function Child() {
const isAdmin = getUser();
return isAdmin ? (
<Confirm />
) : (
<NotFound />
);
}
如上面的代碼所示,如果 isAdmin 為 true,則我呈現確認,如果 isAdmin 為 false,我將呈現 NotFound。
但這將在父組件中呈現 NotFound。
相反,我想重定向到 NotFound。 我該怎么做? 有人可以幫我解決這個問題。 謝謝。
編輯:我試過什么?
return isAdmin ? (
<Confirm />
) : (
<Route component={NotFound} />
);
但這仍然呈現在同一頁面中。
我在主要組件中使用了相同的代碼,如下所示,
function Main() {
return (
<Switch>
<Route
exact
path="/home"
render={routeProps => (
<Layout>
<Home {...routeProps} />
</Layout>
)}
/>
//other routes here
<Route component={NotFound}/> //if none of the urls match then //renders notfound
</Switch>
);
}
我如何使用類似的東西。 謝謝。
如果你使用react-router-dom
react-router
你可以使用如下代碼
如果 isAdmin 為真,我想重定向到頁面“/items”。
下面是我的代碼,
function Child(props) {
const isAdmin = getUser();
return isAdmin ? (
props.history.push('/confirm')
) : (
props.history.push('/notFound')
);
}
您需要在您的 routes.js 或任何聲明路由的路徑/confirm
& notFound
中聲明路由
const Child = (props) => { const isAdmin = getUser(); return (props.history.push(isAdmin? '/confirm': '/notFound'); }
您需要使用history.push
。
您可以使用來自 react-router-dom 的重定向。
import { Route, Redirect } from 'react-router-dom';
const PrivateRoute = () => {
const isAdmin = getUser();
return (
<Route render={isAdmin ? (
<Redirect to='/confirm' />
) : (
<NotFound />
)
} />
)
}
您可以類似地使用 Router Switch 語句。 實現可以在反應路由器文檔中找到: https://reactrouter.com/web/api/Switch
或者,您可以使用 history.push('/404')。 您可以在此問題下找到更多信息: 如何在 React Router v4 中推送到歷史記錄?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.