在 react 中 使用 useEffect 报错:React Hook useEffect has missing dependencies: 'status' and 'token'. Either include them or remove the dependency array react-hooks/exhaustive-deps,怎么解决?
我在useEffect钩子中调用接口
function ChangePassword(props) {
const token = props.match.params.token;
const [state, setState] = useState({
password: '',
confirmPassword: '',
});
const [status, setStatus] = useState({
loaded: false,
auth: false,
});
useEffect(() => {
let { auth } = status;
axios
.get(`http://localhost:2606/api/hostler/changepassword?token=${token}`)
.then((res) => {
console.log('res', res);
auth = res.status === 202;
})
.then(() => setStatus({ auth, loaded: true }))
.catch((err) => console.log('err', err));
}, []);
return (
// code
);
}
但是 react 提示如下警告:
React Hook useEffect has missing dependencies: 'status' and 'token'. Either include them or remove the dependency array react-hooks/exhaustive-deps
也添加status到依赖数组将导致无限循环,因为setStatus在 useEffect 内部调用
不是报错,是警告
提醒你没有给 effect 添加 'status' 和 'token' 的依赖,因为这样的话 'status' 和 'token' 变量改变之后,不会触发 effect 执行
你需要考虑一下,这个是不是合理的