use*_*075 7 typescript reactjs eslint
I'm well aware of what the Hook has missing dependency is, what it means and why it's important to watch all dependencies, but this one is just weird.
export function Compo() {
const [value, setValue] = useState<number>();
useEffect(() => {
setValue(Date.now());
}, []);
return (
<>{value}</>
);
}
Run Code Online (Sandbox Code Playgroud)
works fine, but:
function useValue() {
return useState<number>();
}
export function Compo() {
const [value, setValue] = useValue();
useEffect(() => {
setValue(Date.now());
}, []);
return (
<>{value}</>
);
}
Run Code Online (Sandbox Code Playgroud)
show the well known React Hook useEffect has a missing dependency: 'setValue'. Either include it or remove the dependency array react-hooks/exhaustive-deps.
您在示例中注意到的是规则的一个怪癖react-hooks/exhaustive-deps。它赋予它所知道的钩子特殊的特权,并且知道在某些情况下是“稳定的”。
引用实现:
// Next we'll define a few helpers that helps us
// tell if some values don't have to be declared as deps.
// Some are known to be stable based on Hook calls.
// const [state, setState] = useState() / React.useState()
// ^^^ true for this reference
// const [state, dispatch] = useReducer() / React.useReducer()
// ^^^ true for this reference
// const ref = useRef()
// ^^^ true for this reference
// False for everything else.
Run Code Online (Sandbox Code Playgroud)
具体来说,这部分规则似乎是useState在这些情况下免除钩子设置器的内容:
// Next we'll define a few helpers that helps us
// tell if some values don't have to be declared as deps.
// Some are known to be stable based on Hook calls.
// const [state, setState] = useState() / React.useState()
// ^^^ true for this reference
// const [state, dispatch] = useReducer() / React.useReducer()
// ^^^ true for this reference
// const ref = useRef()
// ^^^ true for this reference
// False for everything else.
Run Code Online (Sandbox Code Playgroud)
钩子的有用/聪明的不幸结果是,它可能会导致推理不起作用的混乱,就像您刚刚描述的场景一样。
| 归档时间: |
|
| 查看次数: |
824 次 |
| 最近记录: |