React+Javascript:-Component will update 被调用太多次导致我的应用程序崩溃

React+Javascript:-Component will update is getting called too many times causing my application to crash

 componentWillUpdate() {
  
  //Axios GET method for getting all the trades

  //Adding data of db into mobx store/or syncing data of db and store
  axios.get(`http://localhost:8091/trade`)
   .then(res => {
    this.props.store.arr = res.data;
   })

 }

这段代码导致我的浏览器崩溃,我的笔记本电脑没有响应。

实际上,每当我尝试通过单击按钮删除包含交易的 table 行时,交易就会被删除,但需要刷新才能看到交易已被删除。

这是因为我的 mobx 存储和数据库不在 sync.So 中,当我刷新(REST api)控制器更新我的 mobx store.After 中的数据时,我可以看到交易被删除。

所以为了消除刷新的需要,我认为使用组件将更新 method.Within 我尝试将 mobx 存储与控制器数据(数据库数据)同步的方法。它有效但导致浏览器占用超过 2.5 GB 的内存,此时所有 运行 应用程序也开始崩溃。

那么达到预期效果的好方法是什么?

注意我不知道为什么 component will update 被调用了太多次。 但是我可以验证它,因为我可以在spring(我的服务器正在向控制器发送数据)中看到(数据库的)选择语句。

将上面的代码放在 component did mount 中并没有消除刷新的需要,但也不会导致浏览器崩溃.

您不应在此生命周期挂钩中执行此类操作。您应该使用 componentDidMount instead for any remote calls that need to happen. However since you are using mobx, you really should not be having these problems as they handle these type of problems for you with the observer pattern. Please read: https://mobx.js.org/getting-started.html 来加快速度,此时应该没有问题。

您的组件 propsstate 中的某些内容导致它经常更新,这导致对 api 的大量调用。最好的办法是找出导致这些更新的原因,并使用提供给 componentWillUpdatenextStatenextProps 参数来检查并仅在需要时发送 api 调用。类似于:

componentWillUpdate(nextProps,nextState) {
   if (nextProps.needToGetApi !== this.props.needToGetApi) {
     //Axios GET here, so that unrelated prop/state change does not cause this to run
   }
}

提示:在 componentWillUpdate 中添加一个断点,然后查看每次调用时发生的 propsstate 突变。