英文:
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:
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])
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论