我正在尝试制作一个按钮来注销用户并将逻辑移动到自定义挂钩useLogout.js。菜单.jsimport useLogout from './useLogout';import UserContext from './UserContext';import TokenContext from './TokenContext';function Menu() { const [user, setUser] = useContext(UserContext); const [token, setToken] = useContext(TokenContext);/* some code....*/ let button; if (token && token.access_token && user) { button = <Button onClick={useLogout}>Logout</Button>; } else { button = <Button>Login</Button>; }/* some code.... */ return( <Nav.Link> {button} </Nav.Link> )}使用Logout.jsimport React, { useContext, useState} from 'react';import UserContext from './UserContext';import TokenContext from './TokenContext';export default function useLogout() { const [user, setUser] = useContext(UserContext); const [token, setToken] = useContext(TokenContext); localStorage.removeItem("token"); localStorage.removeItem("user"); setToken(); setUser();};当我运行它并单击按钮时,我收到此错误:无效的挂钩调用。钩子只能在函数组件内部调用错误:export default function useLogout() {const [user, setUser] = useContext(UserContext);所以我认为我对函数 useLogout 的调用是错误的,所以我修改了我的代码调用,onClick={useLogout()} 而不是onClick={useLogout} 使该行看起来像这样:button = <Button onClick={useLogout()}>Logout</Button>;但随后我收到此错误:有条件地调用 React Hook“useLogout”。React Hooks 必须在每个组件渲染中以完全相同的顺序调用即使我试过:button = <Button onClick={() => useLogout}>Logout</Button>;我怎么能修改我的代码,所以当我点击按钮的功能useLogout从useLogout.js执行?
1 回答
函数式编程
TA贡献1807条经验 获得超9个赞
你想要的可能是这样的:
export default function useLogout() {
const [user, setUser] = useContext(UserContext);
const [token, setToken] = useContext(TokenContext);
return () => {
localStorage.removeItem("token");
localStorage.removeItem("user");
setToken();
setUser();
}
};
/
const logoutCb = useLogout();
button = <Button onClick={logoutCb}>Logout</Button>;
添加回答
举报
0/150
提交
取消