简体   繁体   English

useEffect 的清理函数中的调度动作

[英]Dispatch action in useEffect's cleanup function

I have a form component in a Material UI <Tab /> which allows users to update their address info.我在 Material UI <Tab />中有一个表单组件,它允许用户更新他们的地址信息。 The information is fetched from the API via redux-thunk and the form fields are filled with data from the server before the update has happened.信息是通过redux-thunk从 API 获取的,并且在更新发生之前,表单字段中会填充来自服务器的数据。

在此处输入图像描述

The problem is that after the user fills the fields with new data and updates their address, the form fields still show the previous state and don't update until the user reloads the page.问题是,在用户用新数据填充字段并更新他们的地址后,表单字段仍然显示以前的状态并且在用户重新加载页面之前不会更新。

To fix the problem, I have implemented useEffect to dispatch the action of fetching user data whenever the isUpdated state is true (which will happen after the updateUserAddress action is fulfilled).为了解决这个问题,我实现useEffect以在isUpdated状态为真时调度获取用户数据的操作(这将在updateUserAddress操作完成后发生)。 This, of course, introduced another issue which was infinite rendering.当然,这引入了另一个问题,即无限渲染。

In order to fix the infinite dispatch call, I dispatch an action to clear the update state and set it to false in the useEffect 's cleanup function.为了修复无限调度调用,我调度了一个动作来清除更新状态,并在useEffect的清理函数中将其设置为 false。 This has solved the issue and whenever the user updates their address, the UI updates and the new values populate the form fields:这已经解决了这个问题,每当用户更新他们的地址时,UI 都会更新并且新值会填充表单字段:

  // Refresh user after address update
  useEffect(() => {
    if (updateState) {
      dispatch(getUser(userInfo.user_id));
    }

    // Clear update state
    return () => dispatch(clearUpdateState());
  }, [dispatch, updateState, userInfo]);

The only problem is that the cleanup function is called every time the user changes back and forth from the Edit Address tab.唯一的问题是每次用户从“ Edit Address ”选项卡来回更改时都会调用清理函数。

Although this approach has fixed my problem, I was skeptical about it and wanted to know if this is the right way of doing this.尽管这种方法解决了我的问题,但我对此持怀疑态度,并想知道这是否是正确的方法。

The problem is that after the user fills the fields with new data and updates their address, the form fields still show the previous state and don't update until the user reloads the page.问题是,在用户用新数据填充字段并更新他们的地址后,表单字段仍然显示以前的状态并且在用户重新加载页面之前不会更新。

You can do an optimistic update when the update address action is dispatched and simply write the input data into the state - assuming that the update will probably work.您可以在调度更新地址操作时进行乐观更新,只需将输入数据写入状态 - 假设更新可能会起作用。 This should fill the inputs with the data the user just entered, so for them nothing will change.这应该用用户刚刚输入的数据填充输入,所以对他们来说什么都不会改变。 The update request itself should return the updated data set, so you can save that in redux.更新请求本身应该返回更新的数据集,因此您可以将其保存在 redux 中。 Or if it doesn't, fire a get request right after the update.或者,如果没有,请在更新后立即触发获取请求。

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

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