如何在 ReactJS 的功能组件中声明一个变量
How to declare a variable inside a functionnal component in ReactJS
我有一个变量“myVar”(不是状态)
const myComponent = () => {
const [myState, setMyState] = useState(true)
const myVar = false
return <button onClick={() => {myVar = true} >Click here</button>
}
正如所写,当组件被重新渲染时,myVar
被重新初始化...我想让变量保持它以前的值。我怎样才能得到这种行为?
我找到的解决方案是:
解决方案 1:在组件外部(但不在组件范围内)初始化变量
let myVar = 'initial value';
const myComponent = () => {
....
// myVar is updated sometimes when some functions run
}
解决方案 2:声明组件道具(但 public)
const myComponent = ({myVar = true) => {
....
}
解决此问题的推荐方法是什么?
React 文档建议使用 useRef
来保留任意可变值。所以,你可以这样做:
// set ref
const myValRef = React.useRef(true);
// ...
// update ref
myValRef.current = false;
您想使用解决方案 #1。
代码
let myVar = 'initial value';
const myComponent = () => {
....
// myVar is updated sometimes when some functions run
}
将在渲染之间保留变量 myVar
。
第二个解决方案不起作用。作为道具的变量不维护渲染之间的状态。
我有一个变量“myVar”(不是状态)
const myComponent = () => {
const [myState, setMyState] = useState(true)
const myVar = false
return <button onClick={() => {myVar = true} >Click here</button>
}
正如所写,当组件被重新渲染时,myVar
被重新初始化...我想让变量保持它以前的值。我怎样才能得到这种行为?
我找到的解决方案是:
解决方案 1:在组件外部(但不在组件范围内)初始化变量
let myVar = 'initial value';
const myComponent = () => {
....
// myVar is updated sometimes when some functions run
}
解决方案 2:声明组件道具(但 public)
const myComponent = ({myVar = true) => {
....
}
解决此问题的推荐方法是什么?
React 文档建议使用 useRef
来保留任意可变值。所以,你可以这样做:
// set ref
const myValRef = React.useRef(true);
// ...
// update ref
myValRef.current = false;
您想使用解决方案 #1。
代码
let myVar = 'initial value';
const myComponent = () => {
....
// myVar is updated sometimes when some functions run
}
将在渲染之间保留变量 myVar
。
第二个解决方案不起作用。作为道具的变量不维护渲染之间的状态。