gpt4 book ai didi

reactjs - React useEffect() 仅在具有依赖项的第一次渲染时运行

转载 作者:行者123 更新时间:2023-12-03 14:32:51 25 4
gpt4 key购买 nike

对此还有其他几个 SO 问题,答案是通过 ESLint 消除依赖项投诉(我正在使用 typescript )或做其他事情以仍然允许 useEffect 的第二个参数为 [] .然而,根据 React docs不推荐这样做。同样在 react useEffect 文档下它说

If you pass an empty array ([]), the props and state inside the effect will always have their initial values. While passing [] as the second argument is closer to the familiar componentDidMount and componentWillUnmount mental model, there are usually better solutions to avoid re-running effects too often. Also, don’t forget that React defers running useEffect until after the browser has painted, so doing extra work is less of a problem.



我有以下代码:
  useEffect(() => {
container.current = new VisTimeline(container.current, items, groups, options);
}, [groups, items, options]);

我希望它只运行一次。

是让它每次都运行的唯一方法和 useState跟踪它以前像这样运行过:
  const [didLoad, setDidLoad] = useState<boolean>(false);

useEffect(() => {
if (!didLoad) {
container.current = new VisTimeline(container.current, items, groups, options);
setDidLoad(true);
}
}, [didLoad, groups, items, options]);

最佳答案

我现在处理这个问题的方法是将适当的依赖项放在依赖项列表中。
因为我希望效果只运行一次,并且因为该效果只依赖于组件第一次挂载时的一些数据,所以省略这些依赖关系是完全没问题的。例如,groups prop 以后可能会改变,但是这个效果不需要再次运行。
但是,作为一种习惯,我不会省略推荐的依赖项,我总是列出它们。如果我故意省略某些内容,我会添加一个 eslint ignore 语句(尽管还没有遇到需要这样做的情况)……只要您了解数据更改时发生的情况,这就是您想要遵循的任何约定并且效果确实/不运行。
但是,如果您确实想列出依赖项,我提出的代码也不是最佳解决方案:

 const [didLoad, setDidLoad] = useState<boolean>(false);

useEffect(() => {
if (!didLoad) {
container.current = new VisTimeline(container.current, items, groups, options);
setDidLoad(true);
}
}, [didLoad, groups, items, options]);
当此效果运行时,我不想引起渲染。因此,我将使用 ref(不需要是依赖项)而不是使用状态。
 const timelineLoaded = useRef<boolean>(false);

useEffect(() => {
if (!timelineLoaded.current) {
container.current = new VisTimeline(container.current, items, groups, options);
timelineLoaded.current = true;
}
}, [groups, items, options]);

关于reactjs - React useEffect() 仅在具有依赖项的第一次渲染时运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58054438/

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