reactjs - useEffect Hook 中的值不变
问题描述
这是我的组件:
import { useEffect, useState } from "react";
function Com() {
const [x, setX] = useState(0);
useEffect(() => {
//here is some code that I want to run only once.
//edit: bcz I want to creating variable here and access in setInterval
setInterval(() => {
console.log(x);
//problem is here x not updating
}, 1000);
}, []);
function change() {
console.log(x);
// incrementing x on every click
setX(x + 1);
}
return <button onClick={change}>Change X</button>;
}
export default Com;
我想更新 useEffect Hooks 中 x 的值。如果我使用 x 作为依赖数组, useEffect 中的所有代码都会再次运行我不想要的。
解决方案
您可以通过将函数传递给setState
.
useEffect(() => {
const interval = setInterval(() => {
setX(oldX => /* do something about it */)
}, 1000);
// don't forget to do clean up
return () => clearInterval(interval);
}, []);
推荐阅读
- python - 单击表格单元格时如何在新窗口中打开QWebEngineView?
- c++ - 在 C++ 中为全局变量赋值
- numpy - 关于曲线拟合代码中asterik的问题
- css - Elementor:具有收缩包装效果的柔性列
- python - python烧瓶应用程序上的heroku h10错误消息
- node.js - 如何从 Node 中的两个文件创建单个读取流?
- ruby-on-rails - Rails 6 样式表和 sass 未加载
- linux-kernel - 如何读取 x86 intel 处理器的 PMC(Performance Monitoring Counter)
- typescript - 带有 `rootDirs` 的 Monorepo 会在 `outDir` 中生成不需要的子目录,例如 `src`
- javascript - 有没有办法在javascript循环中强制重绘DOM元素?