javascript - ReactJS:为什么一个状态的值不同?
问题描述
所以我正在使用非常基本的组件进入 Reactjs。我正在从不同的功能中注销相同的状态,但我看到的是不同的值。
import React, { useState, useEffect, useRef } from "react";
const Test = props => {
const [count, setCount] = useState(0);
useEffect(()=>{
setInterval(() => {
console.log("count in interval is:", count);
}, 1000);
},[props]);
function btnClick() {
const newCount = count + 1;
setCount(newCount);
console.log("count changed to: ", newCount);
}
return (
<div>
count is {count}
<br></br>
<button onClick={btnClick}>+</button>
</div>
);
};
export default Test;
一些点击后输出并等待,日志是:
Test.js:8 count in interval is: 0
Test.js:15 count changed to: 1
Test.js:15 count changed to: 2
Test.js:15 count changed to: 3
Test.js:15 count changed to: 4
(8 rows) Test.js:8 count in interval is: 0
我希望两个函数中的“计数”相同。任何人都可以解释这一点吗?
非常感谢。
解决方案
Test
只有一个setInterval
功能,count
即 always 0
。因为它仅在初始渲染期间创建。
它从未创建过另一个setInterval
,因为效果从未[props]
作为依赖项触发。
要setInterval
在每次重新渲染时更改计数:
- 移除依赖
- 在效果内返回一个清理函数
useEffect(
() => {
const t = setInterval(() => {
console.log("count in interval is:", count);
}, 1000);
return () => clearInterval(t); // cleanup on every re-render
}
// no dependency: effect runs on every re-render
);
但是上面的代码会有一个警告:
“缺少
count
依赖”
因此,只需添加count
为依赖项,仅在更改时运行效果。count
useEffect(
() => {
const t = setInterval(() => {
console.log("count in interval is:", count);
}, 1000);
return () => clearInterval(t); // cleanup "old" setInterval
}
, [count] // ony run effect every time count changes
);
推荐阅读
- python - 通过 HTML 渲染掌握 QTableView 中的行高
- python - 根据 Pandas 中的替代组重新排列或改组行
- javascript - 与较大尺寸相比,较小尺寸的视频在网络上的播放速度是否更快?
- javascript - 使用 switch-case 渲染反应钩子
- python - 如何在 Python Flask 网站上创建一个谷歌登录弹出窗口
- c++ - 异构集合
- google-cloud-platform - 对 Google Cloud Console 进行身份验证后,“CheckCookie”302 重定向的标头中的 gidl 查询字符串参数代表什么?
- java - 如何使用 Java 将 Perl 哈希转换为 JSON?
- android-tv - 如何从 Android 源获取 WebOs 应用
- c++ - “bool *”类型的值不能分配给“bool (*)(intenemy_piece)”类型的实体