简体   繁体   English

React UseEffect - 仅在数据更改时执行

[英]React UseEffect - Executing only when data is changed

I know Functions passed to useEffect are executed on every component rendering, i am in a situation where i need useEffect hook not run on initial render but only when these data are rendered => home.matchsPlayed, home.winHome我知道传递给 useEffect 的函数会在每个组件渲染上执行,我处于这样一种情况,即我需要useEffect钩子不在初始渲染时运行,但只有在渲染这些数据时才运行 => home.matchsPlayed, home.winHome

This is my actual situation这是我的实际情况

  useEffect(() => {
    setData(prev =>
      prev.concat([
        {
          day: home.matchsPlayed,
          [selectedHomeName]: home.winHome
        }
      ])
    );
  },[home.matchsPlayed, home.winHome, selectedHomeName]);

  console.log('data', [data]);

Data array looks like this数据数组看起来像这样

在此处输入图像描述

I have seen a solution where i can make use of useRef to keep track of initialMount with useEffect我已经看到了一个解决方案,我可以使用useRef来跟踪initialMountuseEffect

So i changed to所以我改为

const isInitialMount = useRef(true);

  useEffect(() => {
    if (isInitialMount.current) {
       isInitialMount.current = undefined;
    } else {
      setData(prev =>
        prev.concat([
          {
            day: home.matchsPlayed,
            [selectedHomeName]: hhome.winHome
          }
        ])
      );
    }
  },[home.matchsPlayed, home.winHome, selectedHomeName]);

The array has now 1 object less undefined which is slightly better该阵列现在有 1 个 object 少未定义,稍微好一点

在此处输入图像描述

I want my data array being like this, without the first 3 objects undefined because the data are not presented in the initial renderings.我希望我的data array是这样的,没有未定义的前 3 个对象,因为数据没有出现在初始渲染中。 How can i achieve it?我怎样才能实现它?

  Data: [
    {day:22, Sao Paulo: -8},
    {day:16, Sao Paulo: -2},
    {day:27,  Sao Paulo: -9}
  ],

I have reproduced the case here => https://codesandbox.io/s/cool-wind-sism9 (In order to see the demo a chrome extension to unblock the CORS has to be installed, i use CORS Unblock)我在这里复制了这个案例 => https://codesandbox.io/s/cool-wind-sism9 (为了观看演示,必须安装一个 chrome 扩展来解锁 CORS,我使用 Z5A8FEFF0B7023B791DZ)

  useEffect(() => {
    if (!home.matchsPlayed || !home.totalCal || !selectedHomeName) {
      return;
    }

    setData(prev =>
      prev.concat([
        {
          day: home.matchsPlayed,
          [selectedHomeName]: home.totalCal
        }
      ])
    );
  },[home.matchsPlayed, home.totalCal, selectedHomeName]);

Wouldn't that do it?那不就行了吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM