如果条件为true,如何使用react重定向到某个页面



我想重定向到页面"项目";如果isAdmin为true。

下面是我的代码,

function Child() {
    const isAdmin = getUser();
    return isAdmin ? (
        <Confirm />
    ) : (
        <NotFound />
    );
}

如上面的代码所示,如果isAdmin为true,则我呈现confirm,如果isAdmin为false,则我渲染NotFound。

但这将在Parent组件中呈现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为true。

下面是我的代码,

function Child(props) {
    const isAdmin = getUser();
    return isAdmin ? (
       props.history.push('/confirm')
    ) : (
        props.history.push('/notFound')
    );
}

您需要在路径CCD_ 3&routes.js中的notFound或任何声明为的路由

您可以使用来自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语句。实现可以在react router文档中找到:https://reactrouter.com/web/api/Switch

或者,你可以使用history.push('/404'(。你可以在这个问题下找到更多信息:如何在React Router v4中推送到历史?

const Child = (props) => {
    const isAdmin = getUser();
    return (props.history.push(isAdmin ? '/confirm' : '/notFound');
}

您需要使用history.push

最新更新