我正在玩ReacJS。我注意到一件事—— 如果类组件在重新渲染期间类变量的更新值在屏幕中更新,如下所示:
import React, { Component } from "react";
class Temp extends Component {
constructor(props) {
super(props);
this.count = 0;
this.state = {
foo: 0,
};
}
render() {
return (
<button
onClick={() => {
this.setState({ foo: this.state.foo + 1 });
this.count++;
}}
>
{this.count} - {this.state.foo}
</button>
);
}
}
export default Temp;
但是对于函数组件,普通变量的更新值在重新渲染期间不会在屏幕中更新。
import React, { useRef, useState } from "react";
const RefComponent = () => {
const [stateNumber, setStateNumber] = useState(0);
let refVar = 0;
function incrementAndDelayedLogging() {
setStateNumber(stateNumber + 1);
refVar++;
}
return (
<div>
<button onClick={incrementAndDelayedLogging}>Click</button>
<h4>state: {stateNumber}</h4>
<h4>refVar: {refVar}</h4>
</div>
);
};
export default RefComponent;
这就是 React 的实现方式还是我在搞乱什么?我很想知道这件事。 谢谢
最佳答案
React 中的函数式组件没有实例,因此类或实例变量之类的东西不一定有意义;就像其他人在此处的评论中指出的那样,React 将渲染(调用)功能组件并“重置”任何未明确状态的局部变量。 Behavior like instance variables for functional components are achieved with useRef
.
来自文档:
The
useRef()
Hook isn’t just for DOM refs. The “ref” object is a generic container whosecurrent
property is mutable and can hold any value, similar to an instance property on a class.
关于javascript - React 类组件在重新渲染时更新类变量的值,但不更新函数组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61310116/