如何在React Hooks中使用componentWillMount()?

JavaScript

乐Mandy

2020-03-12

在React的官方文档中,它提到-

If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

My question is - how can we use the componentWillMount() lifecyle method in a hook?

第954篇《如何在React Hooks中使用componentWillMount()?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
LEYPro前端 2020.03.12

本·卡尔普(Ben Carp)的回答对我来说似乎只有一个。

但是,由于我们使用的是功能方式,因此可以从闭包和HoC中受益于另一种方法:

const InjectWillmount = function(Node, willMountCallback) {
  let isCalled = true;
  return function() {
    if (isCalled) {
      willMountCallback();
      isCalled = false;
    }
    return Node;
  };
};

然后使用它:

const YourNewComponent = InjectWillmount(<YourComponent />, () => {
  console.log("your pre-mount logic here");
});
乐蛋蛋 2020.03.12

最初的问题的简短答案,如何componentWillMount与React Hooks一起使用:

componentWillMount is deprecated and considered legacy. React recommendation:

Generally, we recommend using the constructor() instead for initializing state.

Now in the Hook FAQ you find out, what the equivalent of a class constructor for function components is:

constructor: Function components don’t need a constructor. You can initialize the state in the useState call. If computing the initial state is expensive, you can pass a function to useState.

So a usage example of componentWillMount looks like this:

const MyComp = () => {
  const [state, setState] = useState(42) // set initial value directly in useState 
  const [state2, setState2] = useState(createInitVal) // call complex computation

  return <div>{state},{state2}</div>
};

const createInitVal = () => { /* ... complex computation or other logic */ return 42; };
SamStafan十三 2020.03.12

https://reactjs.org/docs/hooks-reference.html#usememo

请记住,传递给useMemo的函数在渲染期间运行。不要在渲染时执行通常不会执行的任何操作。例如,副作用属于useEffect,而不是useMemo。

古一凯Gil 2020.03.12

useComponentDidMount挂钩

在大多数情况下useComponentDidMount是要使用的工具。组件已安装(初始渲染)后,它将仅运行一次。

 const useComponentDidMount = func => useEffect(func, []);

useComponentWillMount

重要的是要注意,在类中组件componentWillMount被认为是遗留的。如果您需要代码在组件安装之前仅运行一次,则可以使用构造函数。在这里了解更多由于功能组件没有构造函数的等同性,因此在某些情况下使用钩子在组件挂载前仅运行一次代码可能是有意义的。您可以使用自定义钩子来实现。

const useComponentWillMount = func => {
  const willMount = useRef(true);

  if (willMount.current) {
    func();
  }

  useComponentDidMount(() => {
    willMount.current = false;
  });
};

但是,有一个陷阱。不要使用它来异步设置状态(例如在服务器请求之后。如您所料,它会影响初始渲染,而不会影响初始渲染)。此类情况应以处理useComponentDidMount

演示版

const Component = (props) => {
  useComponentWillMount(() => console.log("Runs only once before component mounts"));
  useComponentDidMount(() => console.log("Runs only once after component mounts"));
  ...

  return (
    <div>{...}</div>
  );
}

完整演示

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android