在ReactJS的功能组件中声明一个变量

时间:2020-10-29 10:07:12

标签: reactjs react-functional-component

我有一个变量“ myVar”(没有状态)

const myComponent = () => {
  const [myState, setMyState] = useState(true)
  const myVar = false

  return <button onClick={() => {myVar = true} >Click here</button>

}

您知道,通过这种方式,如果其他状态发生变化,则将重新渲染组件,然后将重新初始化“ myVar” ...

下面,我找到了解决方法...

解决方案1:在组件外部(但不在组件范围内)初始化变量

const myVar = true
const myComponent = () => {
  ....
}

解决方案2:声明组件属性(但公开)

const myComponent = ({myVar = true}) => {
  ....
}

常规解决方案是什么?

2 个答案:

答案 0 :(得分:2)

使用useRef挂钩。由引用存储的值在重新渲染期间不会重新初始化。更改引用存储的值不会触发重新渲染,因为这不是状态更改。

答案 1 :(得分:1)

好,在类组件中,这可以通过 componentDidMount componentDidUpdate 逻辑来解决。通过使用 useRef useEffect 钩子,可以对功能组件执行相同的操作:

const myComponent = () => {
      const mounted = useRef();
    
    useEffect(() => {
        if (!mounted.current) {
           // do componentDidMount logic
            mounted.current = true;
            const myVar = false
        } else {
          // do componentDidUpdate logic
        }
      });
    }