【发布时间】:2021-01-26 11:32:32
【问题描述】:
我的意图是使用一个函数(由父组件接收,使用useCallback 创建)作为useEffect 中的依赖项,并且仅在函数更改时触发该效果。
考虑以下简单组件:
function MyComponent(props) {
const [myState, setMyState] = useState(0);
useEffect(() => {
setMyState(props.calculate(1));
}, [props.calculate])
return <h1>{myState}</h1>;
}
它在 props 中接收一个函数 calculate 并从中计算 myState。但是我得到了 linting 错误:
React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array.
我不明白为什么 props.calculate 不足以作为依赖项,我们需要 props。我不想使用props,因为这样效果会在每次渲染时重新触发,即使calculate 没有改变。 (假设 calculate 在父级中使用 useCallback 创建)。
以下版本不会出现任何 linting 错误:
function MyComponentVersion2(props) {
const { calculate } = props;
const [myState, setMyState] = useState(0);
useEffect(() => {
setMyState(calculate(1));
}, [calculate])
return <h1>{myState}</h1>;
}
我的问题是:
- 为什么 linter 不能使用
MyComponent? - 与
MyComponentVersion2相比,MyComponent的语义是否存在差异?
我在codesandbox 中做了一个最小的例子
谢谢!
【问题讨论】:
标签: reactjs react-hooks use-effect use-state