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

让人想犯罪 __ 提交于 2019-12-10 04:37:03

问题


I have written a small stateful React component. When this component loads, in componentDidMount method I am making use of Kendo UI to show the content of the component in a popup window.

Here's my code:

export class ErrorDialog extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.errorPopupWindow = null;
    window.addEventListener('resize', this.resizeComponent);
    this.handleWindowKeyDown = this.handleWindowKeyDown.bind(this);
    this.handleButtonCloseWindowOnClick = this.handleButtonCloseWindowOnClick.bind(this);
    this.handleButtonShowDetailsOnClick = this.handleButtonShowDetailsOnClick.bind(this);
    $('#ErrorInformationForm-CloseWindow').focus();
  }

  render() {
    const errorInformation = this.props.errorInformation;
    const baseException = errorInformation.baseException;
    const showExceptionMessage = (typeof baseException !== 'undefined' && typeof baseException === 'object' && baseException !== null
          && typeof baseException.message !== 'undefined' && typeof baseException.message === 'string' && baseException.message !== null
          && baseException.message !== '') ? true : false;
    const baseExceptionMessage = showExceptionMessage ? baseException.message : '';
    const exceptionMessageCss = showExceptionMessage ? 'k-textbox ce-width-100-pct ce-margin-top-5' : 'ce-invisible';
    return(
      <div id="Error-Dialog-Popup" onKeyDown={this.handleWindowKeyDown}>
        <div className="ce-window-body">
          {errorInformation.message}
          <code>
            <textarea readOnly={true} className={exceptionMessageCss} rows="3" defaultValue={baseExceptionMessage} />
          </code>
        </div>
      </div>
    );
  }

  componentDidMount() {
    const errorInformation = this.props.errorInformation;
    const modalWindowTitle = '<span class="ce-width-100-pct ce-app-color-red"><i class="fa ce-fs-1-2-5x fa-times-circle"></i> ' + errorInformation.heading + '</span>';
    $('#Error-Dialog-Popup').kendoWindow({
      actions: [],
      width: 500,
      height: 130,
      visible: true,
      modal: true,
      title: modalWindowTitle,
      resizable: false
    });
    this.resizeComponent();
  }

  resizeComponent() {
  }

  closeWindowIfPossible(evt) {
  }

  handleWindowKeyDown(evt) {
  }

  handleButtonShowDetailsOnClick(evt) {
  }

  handleButtonCloseWindowOnClick(evt) {
  }
}

Given that this component doesn't need to maintain any state, I am trying to convert this component into a stateless functional component.

The place where I am struggling is how to implement componentDidMount functionality? Here's the code I have written so far:

export const ErrorDialog = (props, context) => {
  const errorInformation = props.errorInformation;
  const baseException = errorInformation.baseException;
  const showExceptionMessage = (typeof baseException !== 'undefined' && typeof baseException === 'object' && baseException !== null
        && typeof baseException.message !== 'undefined' && typeof baseException.message === 'string' && baseException.message !== null
        && baseException.message !== '') ? true : false;
  const baseExceptionMessage = showExceptionMessage ? baseException.message : '';
  const exceptionMessageCss = showExceptionMessage ? 'k-textbox ce-width-100-pct ce-margin-top-5' : 'ce-invisible';

  const resizeComponent = () => {
  }

  const closeWindowIfPossible = (evt) => {
  }

  const handleWindowKeyDown = (evt) => {
  }

  const handleButtonShowDetailsOnClick = (evt) => {
  }

  const handleButtonCloseWindowOnClick = (evt) => {
  }

  const handleComponentOnLoad = (evt) => {
    console.log('comes in onLoad');
    const errorInformation = props.errorInformation;
    const modalWindowTitle = '<span class="ce-width-100-pct ce-app-color-red"><i class="fa ce-fs-1-2-5x fa-times-circle"></i> ' + errorInformation.heading + '</span>';
    $('#Error-Dialog-Popup').kendoWindow({
      actions: [],
      width: 500,
      height: 130,
      visible: true,
      modal: true,
      title: modalWindowTitle,
      resizable: false
    });
    resizeComponent();
  }

  return(
    <div id="Error-Dialog-Popup" onLoad={handleComponentOnLoad} onKeyDown={handleWindowKeyDown}>
      <div className="ce-window-body">
        {errorInformation.message}
        <code>
          <textarea readOnly={true} className={exceptionMessageCss} rows="3" defaultValue={baseExceptionMessage} />
        </code>
      </div>
    </div>
  );
}

At first, I thought I could implement componentDidMount kind of functionality in onLoad event handler of the div but when I tried doing it I noticed that the event is not fired at all (I then read the documentation and found out that I can't really use this event :)).

So my questions are:

  • Is there a way to implement componentDidMount kind of functionality in stateless functional components? Essentially what I need to do is do something with the component when it is loaded in DOM.
  • Is what I am trying to do is a valid scenario in case of a stateless functional component or should I just stick with standard component?

回答1:


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.




回答2:


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




回答3:


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`;
}, []);


来源:https://stackoverflow.com/questions/39393140/converting-stateful-react-component-to-stateless-functional-component-how-to-im

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!