reactjs - 如何在函数组件中使用构造函数(胖箭头函数)?
问题描述
我想使用胖箭头函数而不是这个类组件。
class Categories extends Component{
state = {
category : []
}
constructor() {
super();
this.getCategories();
}
getCategories = async () => {
let data = await api.get('/').then(({data})=>data);
this.setState({category:data})
}
render() {
return(
-----
);
}
export default Categories;
我如何在功能组件中使用它
解决方案
import React, { useCallback, useEffect, useState } from 'react';
import PropTypes from 'prop-types';
export const Categories = ({ propA, propB }) => {
const [category, setCategory] = useState([]);
const getCategories = useCallback(async () => {
let res = await api.get('/').then(({data})=>data);
setCategory(res);
}, [setCategory]);
useEffect(() => {
getCategories();
}, []);
return (
<>
<h1>{propA}</h1>
<h1>{prop2}</h1>
<h1>{category}</h1>
</>
);
};
Categories.propTypes = {
propA: PropTypes.string.isRequired,
propB: PropTypes.bool,
};
推荐阅读
- javascript - 第二次搜索后搜索结果未更新 - 反应
- html - 将整个标题部分减小到 45px
- javascript - codeSandBox (React/Node) 的 Http 请求错误
- reactjs - 使用 reactjs 在一个输入字段中键入禁用其他输入字段
- android - Firebase 数据库不存储数据,logcat 没有显示错误
- javascript - 从输入类型 = 文件在数据库(Hibernate、JPA、Spring)中插入字节 []
- javascript - 无法将数据传递到材质对话框 - Angular2+
- android - 应用程序安装期间的 INSTALL_FAILED_SHARED_USER_INCOMPATIBLE 错误
- html - 为什么表格标题不使用宽度设置?
- python - 如何使用 Python 窥探 Google Dataflow / Apache Beam 内部