当数据不更改时,请启发我有关使用效应循环

发布于 2025-02-11 09:37:31 字数 1837 浏览 1 评论 0原文

您好,我有这个组件,经过一些阅读后,我没有估计,当数据中的数据更改时,使用效率再次被调用,但是在我的情况下,这没有变化,我会陷入循环。

export default function Test() {
  
  const [dates, setDates] = useState([]);
  let values = [];
  useEffect(() => {
    getAllFilledJournauxDates().then(function(response) {
      values = response;
      setDates(values);
    }
    );
  }
  , [dates]);
    
  console.log(values);
  


  return(
    <div>
      {dates.map(date => {
        return <div>{date}</div>
      })}
    </div>
  );
}

[edit 2]添加funtion getallfilljournauxdates()

export async function getAllFilledJournauxDates() {
    
        let dates = [];
        let journaux = getAllJournaux()
            .then(response => {
                Object.keys(response).forEach(element => {
                    dates.push(new Date(new Date(response[element].date)).getFullYear() + "-" + (new Date(response[element].date)).getMonth() + "-" + (new Date(response[element].date)).getDate());
                })
            })
        return dates;
}

[edit]

export default function Test() {
  
  const [dates, setDates] = useState([]);
  let values = [];
  useEffect(() => {
    console.log("useEffect"); // displayed two time in console
    getAllFilledJournauxDates().then(function(response) {
      values = response;
      setDates(values);
      console.log(values); //display the array of dates
    }
    );
  }
  , []);
    
  console.log(values); // display an empty array
  


  return(
    <div>
      {dates.map(date => {
        return <div>{date}</div> // display nothing on screen
      })}
    </div>
  );
}

就像由@rowinbot sugger of @rowinbot我删除了阵列中的变量,但是在屏幕上尚无变量,我可以看到该变量已填充在我的控制台中,并且使用效果看起来像是看起来像他被称为两次... 我想补充一点,首先,我尝试用这些值填充日历

Hello i have this component and after some reading i have undestand that the useEffect is called again when data in array change but in my case that's not change and i get into a loop.

export default function Test() {
  
  const [dates, setDates] = useState([]);
  let values = [];
  useEffect(() => {
    getAllFilledJournauxDates().then(function(response) {
      values = response;
      setDates(values);
    }
    );
  }
  , [dates]);
    
  console.log(values);
  


  return(
    <div>
      {dates.map(date => {
        return <div>{date}</div>
      })}
    </div>
  );
}

[EDIT 2] adding the funtion getAllFilledJournauxDates()

export async function getAllFilledJournauxDates() {
    
        let dates = [];
        let journaux = getAllJournaux()
            .then(response => {
                Object.keys(response).forEach(element => {
                    dates.push(new Date(new Date(response[element].date)).getFullYear() + "-" + (new Date(response[element].date)).getMonth() + "-" + (new Date(response[element].date)).getDate());
                })
            })
        return dates;
}

[EDIT]

export default function Test() {
  
  const [dates, setDates] = useState([]);
  let values = [];
  useEffect(() => {
    console.log("useEffect"); // displayed two time in console
    getAllFilledJournauxDates().then(function(response) {
      values = response;
      setDates(values);
      console.log(values); //display the array of dates
    }
    );
  }
  , []);
    
  console.log(values); // display an empty array
  


  return(
    <div>
      {dates.map(date => {
        return <div>{date}</div> // display nothing on screen
      })}
    </div>
  );
}

Like suggered by @rowinbot i have removed the variable in array , but nothing yet on the screen, i can see that the variable is filled in my console, and the useEffect look like he is called two times ...
i want to add that at first i try to fill a calendar with those values but without get the result i wanted i haved render the result most simply

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦忆晨望 2025-02-18 09:37:31

tl; dr:您应该从效果的依赖性数组中删除日期

效果(又称我们传递给useffect Hook的函数)在渲染后的react run上进行效果,依赖关系数组充当运行效果的逃生舱口,以防万一您要运行效果 bolly /strong>在给定渲染中更新某些依赖项后。

在这里,您要说的是,每当日期更新(其值更改)时,您要运行效果,又调用setDates(...)和突变日期值,这会产生组件的渲染,并且由于日期更改了,效果再次运行,并且……这无限期发生。

只需从依赖项数组中删除日期,您就可以了:

  useEffect(() => {
    getAllFilledJournauxDates().then(function(response) {
      values = response;
      setDates(values);
    }
    );
  }
  , []);

只要记住即使依赖性数组都保持空置在开发上会有所不同)并防止循环。

完全避免脱位阵列(省略)会导致相同的结果,一个无限的循环,这告诉反应,在上,每个渲染都需要运行效果,这会导致另一个渲染...和循环永远

您可以在 beta react docs 上做得很好总结其语义。

TL;DR: You should remove dates from the effect's dependency array.

Effects (a.k.a the functions we pass to the useEffect hook) on React runs after rendering, the dependency array acts as a escape hatch for running the effect in case you want to run the Effect only after certain dependencies were updated in a given render.

Here you're saying that whenever dates updates (its value changes) you want to run the Effect which in turn calls setDates(...) and mutates dates value, this produces a render of the component and since dates changed, the Effect is run once more, and... That happens indefinitely.

Just remove dates from the dependency array and you should be fine:

  useEffect(() => {
    getAllFilledJournauxDates().then(function(response) {
      values = response;
      setDates(values);
    }
    );
  }
  , []);

Just remember to keep the dependency array even if its empty, this basically tells React to only run your effect "once" (React 18' strict mode makes this a bit different on development) and prevents the loop.

Avoiding the depedency array entirely (omitting it) would result in the same outcome, an infinite loop, this tells React that on every render, you want to run the effect, which causes another render... And cycles eternally.

You can read more about Effects in the beta React docs which does a great job summarizing its semantics.

假装爱人 2025-02-18 09:37:31

您正在更新使用效果内的日期,这是您更改日期的每一个使用效率重新运行的方法,这会导致它再次重新运行并创建循环。尝试将其他内容触发使用效果而不是日期触发。也许您可以尝试将其更改为“值”,而不是使用日期,并在使用效率之外提取响应,并将其置于值。

useEffect(() => {
      setDates(values);
  }
  , [values]);
    
  console.log(values);

You are updating dates inside the useEffect, and that is way on every useEffect rerun you change the dates and that causes it to rerun again and creates a loop. Try to put something else to trigger the useEffect instead of the dates. Maybe you can try to put it on change of "values" instead of dates and fetch response outside of useEffect and put it in values.

useEffect(() => {
      setDates(values);
  }
  , [values]);
    
  console.log(values);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文