gpt4 book ai didi

javascript - useEffect 抛出依赖警告

转载 作者:行者123 更新时间:2023-11-29 18:40:35 25 4
gpt4 key购买 nike

我有一个具有受控状态的下拉菜单。如果用户更改了下拉值并且输入不为空,则触发从其他组件传递的函数。

export default ({ triggerChange, inputVal }) => {
const [dropdown, setDropdown] = useState(1);

useEffect(() => {
if (inputVal) {
triggerChange(dropdown);
}
}, [dropdown]); // this line throw a warning

const handleChange = e => {
setDropdown(e.target.value);
};

return (
<div>
<select onChange={handleChange}>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
);
};

codesandbox

错误

React Hook useEffect has missing dependencies: 'inputVal' and 'triggerChange'. Either include them or remove the dependency array. If 'triggerChange' changes too often, find the parent component that defines it and wrap that definition in useCallback. (react-hooks/exhaustive-deps)

最佳答案

将这些添加到依赖项中:

useEffect(() => {
if (inputVal) {
triggerChange(dropdown);
}
}, [dropdown, inputVal]);

这只会在 dropdowninputVal 值发生变化时重新运行效果。

对于triggerChange:

如果 dropdown 经常变化,使用 useCallback 钩子(Hook)。

// Parent.js
const memoizedTriggerChange = useCallback(
() => {
triggerChange(dropdown);
},
[dropdown],
);

useEffect(() => {
if (inputVal) {
memoizedTriggerChange();
}
}, [inputVal]);

编辑

基于OPs codesandbox

// index.js
const triggerChange = useCallback(() => {
console.log("call api");
}, []); // not depending on inputVal to prevent firing if inputVal changes

// AnotherComp.js
useEffect(() => {
triggerChange(dropdown);
}, [dropdown, triggerChange]);

关于javascript - useEffect 抛出依赖警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57386586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com