react的生命周期componentWillMount,改成react hooks写法,里面的代码写在什么地方?

react的生命周期componentWillMount,改成react hooks写法,componentWillMount()生命周期里面的代码写在什么地方?

比如下面这个示例:

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'));
阅读 8.2k
3 个回答

自定义hook

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

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

  willMount.current = false;
};

使用

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

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

其实componentWillMount 这个阶段属于挂载钱最后阶段,这个方法可以直接写到函数体内部。但是只执行一次。需要一个辅助变量来判断。

clipboard.png

这里是hooks和钩子对应内容,实际上是否这个willmount 并不在钩子生命周期内

推荐问题