Redux Thunk操作未执行



我使用React与Redux和Thunk作为中间件来处理异步操作。我有一个按钮,当用户点击它时,它应该注销用户。目前,当我点击按钮时,什么都没有发生。我在attemptLogout中添加了一个console.log,但即使这样也不会触发。。。我不知道为什么,希望有人能审查我的代码并提供一些反馈。

NavProfile.js

const onLogout = () => {
attemptLogout();
};
<Menu.Item key={menuItem.legth + 1} onClick={onLogout}>
<span>
<LogoutOutlined className="mr-3" />
<span className="font-weight-normal">Logout</span>
</span>
</Menu.Item>

redux/actions/Auth.js

export const logout = () => ({
type: LOGOUT,
});

redux/reducers/Auth.js

const initialState = {
token: localStorage.getItem('token'),
isAuthenticated: false,
loading: true,
error: {},
};
const auth = (state = initialState, action) => {
const { type, payload } = action;
switch (type) {
...
case LOGOUT:
return {
...state,
token: null,
isAuthenticated: false,
loading: false,
};
default:
return state;
}
};

redux/reducers/User.js

const initialState = {
user: null,
loading: true,
error: {},
};
const user = (state = initialState, action) => {
const { type, payload } = action;
switch (type) {
...
case LOGOUT:
return {
...state,
loading: false,
user: null,
};
default:
return state;
}
};

redux/thunks/Auth.js

// Logout User
export const attemptLogout = () => async (dispatch) => {
console.log('Logout');
dispatch(logout());
dispatch(push('/auth/login'));
};

您需要调度attemptLogout。否则,thunk永远不会通过redux中间件,也永远不会被调用。

const onLogout = () => {
dispatch(attemptLogout());
};

要访问调度,您可以使用菜单/菜单项组件中的钩子。类似于:

import {useDispatch} from 'react-redux';
function MenuExample() {
const dispatch = useDispatch();
const onLogout = () => {
dispatch(attemptLogout());
};
...
}

相关内容

  • 没有找到相关文章

最新更新