reactjs - 如何将此类组件更改为功能组件?
问题描述
我正在尝试将我的所有类组件转换为功能组件。我正在使用 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 };
解决方案
好吧,为了使用钩子将基于类的组件转换为功能组件,对于this.state
类组件中的每个字段,您都使用useState
调用。
由于componentDidMount
dosent 存在于功能组件中,因此您可以使用useEffect
which 作为 、 和 的componentDidMount
替代componentDidUpdate
品componentWillUnmount
。
所以组件看起来像这样
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 };
推荐阅读
- networking - 通过 IP 访问 IISExpress 以获取 asp.net 核心 API
- java - 如何修复此内存泄漏(IntentService、Runnable、ObjectBox、Repository)?
- python - 数据科学 - 模型推荐
- python - 如何查找输入字符串中常见字符的数量
- c++ - 没有调用函数,而是使用了垃圾值。如何调用函数并解决问题?
- html - 为什么我的 HTML 网页有时会显示原始代码
- r - 我的数据框中具有连续数据类型的属性的等宽离散化和分类
- mysql - 左连接没有给出预期的结果
- .net - React Native:调用在 localhost 上运行的 API
- ios - Swift iOS Stripe - 当过期或 CVV 字段处于活动状态且卡号字段为空时如何关闭键盘