如何在 ReactJS 的功能组件中声明变量

IT技术 javascript reactjs react-hooks constants state
2021-05-14 11:44:13

我有一个变量“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) => {
  ....
}

解决此问题的推荐方法是什么?

2个回答

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渲染之间的变量

第二种解决方案不起作用。作为props的变量不维护渲染之间的状态。