ESlint配置文件
umi项目下配置:
{
"extends": "eslint-config-umi",
"rules": {
// "react-hooks/exhaustive-deps": 0 注释这行即开启校验
}
}
1.warning React Hook useEffect has a missing dependency: ‘XXX’. Either include it or remove the dependency array
问题代码块:
const dispatch = useDispatch();
const init = () => {
dispatch({
type: 'cashInterest/clearCache',
});
}
useEffect(() => {
init();
}, []);
官方文档说明:
解决方法:
1)在effect 内部去声明它所需要的函数,适用于只需要调用一次的函数,比如初始化函数等。
const dispatch = useDispatch();
useEffect(() => {
const init = () => {
dispatch({
type: 'cashInterest/clearCache',
});
}
init();
}, [dispatch]);
2)使用useCallback定义依赖项,确保自身依赖改变函数主体也会改变。
const dispatch = useDispatch();
const init = useCallback( () => {
dispatch({
type: 'cashInterest/clearCache',
});
},[dispatch])
useEffect(() => {
init();
}, [init]);
const otherFunc = () => {
init();
}
2.warning ‘setInitValue’ is assigned a value but never used no-unused-vars
问题代码块:
//初始化一个值
const [initValue, setInitValue] = useState(0);
useEffect(() => {
console.log(initValue);
}, [initValue]);
官方文档说明:
解决方法:
const initValue = useRef(0);
useEffect(() => {
console.log(initValue.current);
}, []);
当然也可以使用其他原生js变量定义。