The life cycle of react componentWillMount is changed to react hooks. Where is the code written in it?

the life cycle componentWillMount of react is changed to react hooks. Where is the code in the life cycle of componentWillMount () written?

for example, the following example:

import React from "react";
import ReactDOM from "react-dom";
import { createForm, formShape } from "rc-form";

class Form extends React.Component {
  static propTypes = {
    form: formShape,
  };

  componentWillMount() {
    this.nameDecorator = this.props.form.getFieldDecorator("name", {
      initialValue: "",
      rules: [{
        required: true,
        message: "What\"s your name?",
      }],
    });
  }

  onSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((error, values) => {
      if (!error) {
        console.log("ok", values);
      } else {
        console.log("error", error, values);
      }
    });
  };

  onChange = (e) => {
    console.log(e.target.value);
  }

  render() {
    const { getFieldError } = this.props.form;

    return (
      <form onSubmit={this.onSubmit}>
        {this.nameDecorator(
          <input
            onChange={this.onChange}
          />
        )}
        <div style={{ color: "red" }}>
          {(getFieldError("name") || []).join(", ")}
        </div>
        <button>Submit</button>
      </form>
    );
  }
}

const WrappedForm = createForm()(Form);
ReactDOM.render(<WrappedForm />, document.getElementById("__react-content"));
Jul.01,2022

Custom hook

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

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

  willMount.current = false;
};

use

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

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

in fact, the componentWillMount stage belongs to the last stage of mounting money, and this method can be written directly into the function body. But only once. An auxiliary variable is needed to judge.

clipboard.png

here is the corresponding content of hooks and hook. In fact, whether this willmount is not within the life cycle of the hook


http://projects.wojtekmaj.pl/...
seems to have been abandoned

Menu