简体   繁体   English

React.js “useEffect” 不定式循环

[英]React.js “useEffect” infinitive loop

I'm using a function which needs to update data table and gets values from an API using fetch.我正在使用 function 需要更新数据表并使用 fetch 从 API 获取值。 When the page uploads, data comes perfectly with useEffect but i want it to be uploaded when i delete or add item into the table which doesn't work right now as it goes into infinitive loop.当页面上传时,数据与 useEffect 完美结合,但我希望在我删除或将项目添加到表中时上传它,因为它进入不定式循环,所以现在无法正常工作。

const [data,setData] = useState();


 useEffect(() => {
   
   PersonService.getAllPersonList()
   .then(res => {
     setData(res)
     console.log(res)
   }
 )
 }, [data]); 

Take a step back and consider what you are semantically telling the code to do.退后一步,考虑一下你在语义上告诉代码做什么。 useEffect basically means, "Perform this operation whenever this dependency has changed." useEffect基本上意味着,“只要此依赖项发生更改,就执行此操作。”

What is the operation in your case?你的情况是什么操作?

  • Populate the data state value.填充data state 值。

And what is the dependency?什么是依赖?

  • The data state value. data state 值。

So you're telling the code to populate data (an operation which by definition changes data ) any time data has changed.因此,您要告诉代码在data发生更改时填充data (根据定义更改data的操作)。

Why?为什么?

Since the only dependency is data then it sounds like you just want this to happen once when the component is first mounted.由于唯一的依赖项是data ,因此听起来您只希望在首次安装组件时发生一次 For that you would use an empty dependency array:为此,您将使用一个空的依赖数组:

useEffect(() => {
  // your operation
}, []);

After that, any time data has changed then why are you re-fetching data ?在那之后,任何时候data都发生了变化,那你为什么要重新获取data Your local copy has changed.您的本地副本已更改。 Do you not want to retain those changes?您不想保留这些更改吗? Did you also change the data on the server and want to completely refresh everything?您是否还更改了服务器上的数据并想要完全刷新所有内容? In either event, this isn't the approach you'd want to use.无论哪种情况,这都不是您想要使用的方法。

Most likely, whichever operation modified the source of data on the server should return the updated data and the client-side code which invoked that operation can then update data with that returned value.最有可能的是,无论哪个操作修改了服务器上的data源,都应该返回更新的数据,然后调用该操作的客户端代码可以使用该返回值更新data

Your useEffect is subscribed to ' data ', which you are also updating in the useEffect.您的 useEffect 订阅了“数据”,您也在 useEffect 中对其进行了更新。

When ' data ' updates, the useEffect runs.当“数据”更新时,useEffect 运行。 Because the useEffect is updating ' data ' you have an infinite loop.因为 useEffect 正在更新“数据”,所以你有一个无限循环。

If you want the useEffect to only run once on load, simply remove the data subscription from the useEffect.如果您希望 useEffect 仅在加载时运行一次,只需从 useEffect 中删除数据订阅即可。

useEffect(() => {
   
   PersonService.getAllPersonList()
   .then(res => {
     setData(res)
     console.log(res)
   }
 )
 }, []); 

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

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