首页 > 解决方案 > 如何在函数组件中使用构造函数(胖箭头函数)?

问题描述

我想使用胖箭头函数而不是这个类组件。

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;

我如何在功能组件中使用它

标签: reactjsreact-hooksuse-statereact-functional-component

解决方案


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,
};

推荐阅读