不接收最后状态值

huangapple go评论70阅读模式
英文:

Don't receive the last state value

问题

我有一个名为useMetrics的自定义钩子,它有两个主要功能:

  • updateMetricsBy:修改一个本地状态,该状态将用于保存数据到服务器
  • saveMetrics:将数据保存到服务器

问题在于,saveMetrics 以某种原因接收到了一个旧的度量状态值。这就是为什么我们可以调查第一次调用不会在服务器上更新任何内容的原因:

控制台截图

Codesandbox 链接:https://codesandbox.io/s/spring-browser-nynxp7?file=/src/App.js

英文:

I have a custom hook called useMetrics which has 2 main functions:

  • updateMetricsBy: modifies a local state which will be used to save data to the server
  • saveMetrics: saves data to the server

The problem is saveMetrics receives an old metrics state value for some reason. That's why we can investigate that the first calling won't update anything on the server:

console picture

Codesandbox link: https://codesandbox.io/s/spring-browser-nynxp7?file=/src/App.js

答案1

得分: 1

在当前代码中,你不得不将其视为先前的状态值。一个函数用于更新状态并通过回调函数来检查状态。这意味着状态是异步工作的,不会再次渲染。因此,你不能看到已更新的值,因为它调用的是未重新渲染的值。

以下是正确验证已更新值的方法:

const useMetrics = () => {
// ...
  useEffect(() => {
    console.log("!!已保存 [metrics]", metrics);
  }, [metrics])
}
英文:

In the current code, you have no choice but to view it as the previous state value. One function is to update the status and check the status through callback. This means that the state works asynchronously and is not rendered again. Therefore, you cannot see the updated value because it calls the value that has not been re-rendered.

Here's how you can correctly verify the updated values.

const useMetrics = () => {
// ...
  useEffect(() => {
    console.log("!!Saved [metrics]", metrics);
  },[metrics])
}

huangapple
  • 本文由 发表于 2023年7月20日 09:48:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76726177.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定