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

Declare a variable inside a functional component in ReactJS

我有一个变量“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:声明组件道具(但 public)

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

正则解是什么?

使用 useRef 钩子。在 re-render 期间不会重新初始化引用存储的值。更改引用存储的值不会触发 re-render,因为它不是状态更改。

好的,在 class 组件中,这可以通过 componentDidMountcomponentDidUpdate 逻辑来解决。通过使用 useRefuseEffect 挂钩,功能组件可以完成相同的行为:

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