在react中初始化函数遇到的惰性初始化问题

1,316 阅读1分钟

一、前言

useState可以初始化一些参数,如果我们初始化的参数是一个函数的话会怎么样呢,这是我今天遇到的一个问题。

import { useState } from "react";

export default function App() {
  const [func, setFunc] = useState(() => alert(1));
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

如上述代码,点击在沙盒中运行代码,我们给参数func定义一个初始化的函数,但是项目一运行,发现他就执行了alert(1)???

image-20220309213239811

为什么我们执行定义的函数,他却执行了呢。

 👇

二、惰性初始 state

initialState 参数只会在组件的初始渲染中起作用,后续渲染时会被忽略。如果初始 state 需要通过复杂计算获得,则可以传入一个函数,在函数中计算并返回初始的 state,此函数只在初始渲染时被调用:

const [state, setState] = useState(() => {
  const initialState = someExpensiveComputation(props);
  return initialState;
});

上述⬆️从官网内容截取。由此可知,在react中,useState中参数是一个方法是有其他意义的。

react会误以为我们是在做惰性初始化

三、怎么初始化一个方法

3.1 方法一

由上述2中得知,在惰性初始化函数中返回的值即为初始化的值,那么我们就可以这样写, 再套一层函数体

import { useState } from "react";

export default function App() {
  const [func, setFunc] = useState(() => () => alert(1));

  console.log(func);
  return (
    <div className="App">
      <button onClick={func}>执行方法</button>
    </div>
  );
}

3.2 方法二 使用 useRef

import { useRef } from "react";

export default function App() {
  const funcRef = useRef(() => alert(1));
  const func = funcRef.current;
  return (
    <div className="App">
      <button onClick={func}>执行方法</button>
    </div>
  );
}