gpt4 book ai didi

reactjs - 使用 Prop 值删除 useEffect Hook 中状态数组元素中的元素

转载 作者:行者123 更新时间:2023-12-04 07:21:23 26 4
gpt4 key购买 nike

我正在尝试使用传入组件的 Prop 从 useEffect 中的状态变量中删除项目。我想从状态变量中获取初始值,然后删除该数组中的元素并将状态变量再次设置为新值。但是,当我不在依赖项数组中传递状态变量时,它会抛出警告,因为 React Hook useEffect 缺少依赖项:'abc'。要么包含它,要么删除依赖数组,当我传递它时,它进入无限循环,我认为这是正确的,因为 useeffect 工作。这是我正在尝试的使用效果:

const [abc, setAbc] = useState([]);

useEffect(() => {
axios.get(url).then(res => setAbc(res));
}, [props.bbb])

useEffect(() => {
if(props.xyz) {
let aaa = abc.filter(key => key.id === props.xyz);
setAbc(aaa);
}
}, [props.xyz])

我在这里遗漏了什么吗?有没有更好的方法来做到这一点?

提前致谢。

最佳答案

正确,包括效果更新可能导致渲染循环的依赖项。使用功能状态更新来消除将 abc 作为依赖项的需要。

useEffect(() => {
if (props.xyz) {
setAbc(abc => abc.filter(key => key.id === props.xyz));
}
}, [props.xyz]);

因为第一个 useEffect 实际上并没有引用 props 我可能会假设你打算只在挂载时调用它。您可以使用空的依赖项数组来执行此操作。

useEffect(() => {
axios.get(url).then(res => setAbc(res));
}, []);

更新

如果你想获取 abc 并在每次 props.xyz 依赖项更新时进行过滤,那么使用一个 useEffect 钩子(Hook)并过滤更新状态前的结果。

useEffect(() => {
axios.get(url)
.then(res => {
if (props.xyz) {
setAbc(res.filter(key => key.id === props.xyz));
} else {
setAbc(res);
}
});
}, [props.xyz]);

关于reactjs - 使用 Prop 值删除 useEffect Hook 中状态数组元素中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68479718/

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