[英]ReactJS: Why different values from one state?
所以我正在使用非常基本的组件进入 Reactjs。 我正在从不同的功能中注销相同的 state,但我看到的是不同的值。
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;
Output 经过一些点击和等待,日志是:
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
function 其中count
始终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
);
count
的值不会改变,这是预期的行为,虽然不是很明显。
看,您甚至count
声明为const count
,它是不可变的。 相反,发生的是在第一次渲染count
被赋值为0
。 count
的值永远不会改变,而是每次更改 state 时都会调用组件Test
,并且 function useState
为常量count
分配不同的值,每次都是新常量。
因此,在第一次渲染期间, const count
的值被setInterval
调用的 function 内的闭包捕获,并且该值永远保持0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.