Converting stateful React component to stateless functional component: How to implement “componentDidMount” kind of functionality?

时光总嘲笑我的痴心妄想 提交于 2019-12-05 07:54:37

Functional stateless components do not have lifecycle methods. You should stick with standard component in this case.


From React's documentation:

These components must not retain internal state, do not have backing instances, and do not have the component lifecycle methods.

What they said (above), but also consider making a stateful component container and passing props/args to subcomponents which are stateless.

In React 16.8, you can now use State Hooks for functional components. For componentDidMount, it's recommended to use Effect Hooks.

import React, { useState, useEffect } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]); // Only re-run the effect if count changes)

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Demo: https://codepen.io/anon/pen/QPYMbK

If you want the Effect Hook to only run after mount, use an empty array as the condition:

useEffect(() => {
  document.title = `You clicked ${count} times`;
}, []);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!