【问题标题】:Why React Doesn't Redirect to route?为什么 React 不重定向到路由?
【发布时间】:2021-01-17 07:29:10
【问题描述】:

我正在使用 React 和 BrowserRoute 组件,当我使用这种方式时不会重定向到 Route 例如:

...//Code
<BrowserRouter>
  <Switch>
    <Route path="/" exact component={Home}/>
    <Route path="/profile" exact component={Profile}/>
    <Route path="/login" exact component={Login}/>
  </Switch>
</BrowserRouter>

在这个功能组件中,我有以下代码:

登录组件

const Login = () => {
    const loginContext = useContext(LoginContext);
    if (loginContext.isAuth) {
        return <Redirect to='/profile' />
    }
    const authUser = () => {
        loginContext.authUser();
    }

    return (
        <div className="row">
            <div className="col">
            ...
   );

配置文件组件

const Profile = () => {
    const loginContext = useContext(LoginContext);
    const logOut = () => {
        loginContext.logOut()
        **return <Redirect to='/login' />**
    }
    **if (!loginContext.isAuth) {**
        return <Redirect to='/login' />
    }
    return (
        <div className="row">
            <div className="col">
            ...
    );

如果我在单击 &lt;Button ... onClick={logOut} &gt;Log Out&lt;/Button&gt; 之类的按钮时向 logOut 函数添加一些逻辑,则不会重定向到登录组件 但是当 loginContext.isAuth 为假时,组件运行良好并重定向...... 我使用和未使用 Switch Component,在 Route render={...} 和 component={...} 处渲染,但是当我单击 LogOut 按钮时想要重定向时不起作用,只有当 loginContext.isAuth 为 true 时o 假的...

PSD:对不起我的英语:'(

【问题讨论】:

    标签: reactjs react-router react-hooks react-router-dom


    【解决方案1】:

    您使用的是react-router-dom,对吗? 路由,如果您不需要可点击链接而是从代码路由,最好使用react-router-dom 公开的useHistory 组件完成。

    例如:

    import { useHistory } from 'react-router-dom';
    
    const Profile = () => {
        const loginContext = useContext(LoginContext);
        const history = useHistory();
    
        const logOut = () => {
            loginContext.logOut()
            history.push({pathname: '/login'});
        }
    
        if (!loginContext.isAuth) {
            history.push({pathname: '/login'});
        }
    
        return (
            <div className="row">
                <div className="col">
                ...
        );
    

    【讨论】:

      猜你喜欢
      • 2019-04-03
      • 2019-06-24
      • 2021-07-24
      • 2023-02-03
      • 1970-01-01
      • 2018-02-15
      • 1970-01-01
      • 2021-09-09
      • 2015-09-30
      相关资源
      最近更新 更多