首页 > 解决方案 > 如何将此类组件更改为功能组件?

问题描述

我正在尝试将我的所有类组件转换为功能组件。我正在使用 redux 来处理我的状态,但我还不太熟悉功能组件。如何将此 Class 组件转换为功能组件?

class PersonnelPage extends Component {
  state = {
    isLoading: false,
  };

  constructor(props) {
    super(props);
  }
  componentDidMount() {
    this.props.getEmployees();
  }

  handleDeleteEmployee(id) {
    return (e) => this.props.deleteEmployee(id);
  }
  render() {
    const { employees } = this.props;
    return (
      <>
      </>
    );
  }
}

function mapState(state) {
  const employees = state;
  return employees;
}

const actionCreators = {
  getEmployees: employeeActions.getAll,
  deleteEmployee: employeeActions.delete,
};

const connectedPersonnelPage = connect(mapState, actionCreators)(PersonnelPage);
export { connectedPersonnelPage as PersonnelPage };

标签: reactjsreact-redux

解决方案


好吧,为了使用钩子将基于类的组件转换为功能组件,对于this.state类组件中的每个字段,您都使用useState调用。

由于componentDidMountdosent 存在于功能组件中,因此您可以使用useEffectwhich 作为 、 和 的componentDidMount替代componentDidUpdatecomponentWillUnmount

所以组件看起来像这样


function PersonnelPage(props) {
    const [isLoading, setIsLoading] = useState(false);

    useEffect(() => {
        props.getEmployees();
    }, [props.getEmployees]);

    const handleDeleteEmployee = id => {
        return e => props.deleteEmployee(id);
    };
    return <></>;
}

function mapState(state) {
    const employees = state;
    return employees;
}

const actionCreators = {
    getEmployees: employeeActions.getAll,
    deleteEmployee: employeeActions.delete,
};

const connectedPersonnelPage = connect(mapState, actionCreators)(PersonnelPage);
export { connectedPersonnelPage as PersonnelPage };

推荐阅读