我有一个变量“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:声明一个组件props(但公开)
const myComponent = ({myVar = true) => {
....
}
解决此问题的推荐方法是什么?