简体   繁体   English

如何在函数组件(胖箭头函数)中使用构造函数?

[英]how can i use constructor in function component (fat arrow function)?

I want to use fat arrow function instead of this class component.我想使用胖箭头函数而不是此类组件。

in function component it gives error while defining constructor function and super() .在函数组件中,它在定义构造函数和super()出错。

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;

how can i use this in function 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,
};

In functional components you can use a hook which is called useEffect and with this you can implement something like constructors in call components在功能组件中,你可以使用一个叫做useEffect的钩子,通过这个你可以在调用组件中实现类似构造函数的东西

 import React,{useEffect} from "react" function App (){ useEffect(() => {console.log("useEffect")},[]) return <h1>Hello world</h1> }

note that useEffect function also takes second argument (an array) which indicates that when first arg (function that we passed) should fire.请注意, useEffect 函数还接受第二个参数(一个数组),它表示第一个参数(我们传递的函数)应该何时触发。 when you pass an empty array the function inside useEffect only run the first time components is mounted当您传递一个空数组时,useEffect 内的函数仅在第一次安装组件时运行

you can read more about this on react docs https://reactjs.org/docs/hooks-effect.html您可以在 react docs https://reactjs.org/docs/hooks-effect.html上阅读有关此内容的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM