简体   繁体   English

为什么我的 handleLogout 功能在我的 react 应用程序中不起作用?

[英]Why won't my handleLogout funtion work in my react app?

I am trying to implement user auth, using react, react redux, and axios.我正在尝试实现用户身份验证,使用反应、反应 redux 和 axios。 My problem right now is when I click my logout button on my header, I want it to remove both access and refresh tokens from local storage, that get set at login.我现在的问题是,当我单击 header 上的注销按钮时,我希望它从本地存储中删除访问和刷新令牌,这些令牌在登录时设置。 With the code I have now, I get no errors, but nothing happens when logout button gets clicked.使用我现在拥有的代码,我没有收到任何错误,但是单击注销按钮时没有任何反应。

My handleLogout function:我的句柄注销 function:

    const history = useHistory();

    const handleLogout = () => {
        logout(history);
    };

my logout action that the above function uses:上述 function 使用的我的注销操作:

export const logout = (history) => (dispatch) => {
    localStorage.removeItem('access_token');
    localStorage.removeItem('refresh_token');
    console.log('Made it here');
    dispatch({
        type: LOGOUT_SUCCESS,
    });
    history.push('/');
};

It seems to never reach this action as my console.log('made it here') never gets outputted.似乎永远不会执行此操作,因为我的 console.log('made it here') 永远不会被输出。

material ui button with onClick set to use function: onClick 设置为使用 function 的材质 ui 按钮:

<Button
color="primary"
variant="outlined"
className={classes.link}
onClick={handleLogout}
>
    Logout
</Button>

Since your logout function returns an arrow function, and that function expects an argument dispatch , you also need to pass-in that argument in order to work.由于您的logout function 返回一个箭头 function,并且 function 需要一个参数dispatch才能工作,因此您还需要传入该参数。

import { useHistory } from 'react-router-dom';
import { useDispatch } from 'react-redux';

// inside your component
const history = useHistory();
const dispatch = useDispatch();

function handleLogout() {
    logout(history)(dispatch);
};

Depending on your implementation, you might also import your dispatch dependency directly, and not pass-in it as an argument, so you can avoid returning a function which returns another function.根据您的实现,您还可以直接导入您的调度依赖项,而不是将其作为参数传递,因此您可以避免返回 function ,后者返回另一个 function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM