功能组件内部的ReactJS生命周期方法

reactjs React.js

梅卡卡西Eva

2020-03-12

与其在类中编写组件,不如使用函数语法。

如何覆盖componentDidMountcomponentWillMount内部的功能部件?
可能吗

const grid = (props) => {
    console.log(props);
    let {skuRules} = props;

    const componentDidMount = () => {
        if(!props.fetched) {
            props.fetchRules();
        }
        console.log('mount it!');
    };
    return(
        <Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
            <Box title="Sku Promotion">
                <ActionButtons buttons={actionButtons} />
                <SkuRuleGrid 
                    data={skuRules.payload}
                    fetch={props.fetchSkuRules}
                />
            </Box>      
        </Content>  
    )
}

第1215篇《功能组件内部的ReactJS生命周期方法》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
飞云Mandy飞云 2020.03.12

如果您使用react 16.8,则可以使用react Hooks ... React Hooks是使您可以“挂钩”功能组件中的React状态和生命周期功能的函数... docs

理查德十三Davaid 2020.03.12

您可以创建自己的生命周期方法。

实用功能

import { useEffect, useRef } from "react";

export const componentDidMount = handler => {
  return useEffect(() => {
    return handler();
  }, []);
};

export const componentDidUpdate = (handler, deps) => {
  const isInitialMount = useRef(true);

  useEffect(() => {
    if (isInitialMount.current) {
      isInitialMount.current = false;

      return;
    }

    return handler();
  }, deps);
};

用法

import { componentDidMount, componentDidUpdate } from "./utils";

export const MyComponent = ({ myProp }) => {
  componentDidMount(() => {
    console.log("Component did mount!");
  });

  componentDidUpdate(() => {
    console.log("Component did update!");
  });

  componentDidUpdate(() => {
    console.log("myProp did update!");
  }, [myProp]);
};  

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android