函数组件内的 ReactJS 生命周期方法 [英] ReactJS lifecycle method inside a function Component

查看:55
本文介绍了函数组件内的 ReactJS 生命周期方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用函数语法,而不是在类中编写组件.

Instead of writing my components inside a class, I'd like to use the function syntax.

如何在函数组件中覆盖componentDidMountcomponentWillMount?
甚至有可能吗?

How do I override componentDidMount, componentWillMount inside function components?
Is it even possible?

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>  
    )
}

推荐答案

随着 Hooks 可以实现生命周期类型的行为以及功能组件中的状态.目前

With the introduction of Hooks it is possible to implement a lifecycle kind of behavior as well as the state in the functional Components. Currently

Hooks 是一个新的特性提案,可以让你使用 state 和其他无需编写类即可响应功能.它们作为 v16.8.0

Hooks are a new feature proposal that lets you use state and other React features without writing a class. They are released in React as a part of v16.8.0

useEffect 钩子可用于复制生命周期行为,useState 可用于在函数组件中存储状态.

useEffect hook can be used to replicate lifecycle behavior, and useState can be used to store state in a function component.

基本语法:

useEffect(callbackFunction, [dependentProps]) => cleanupFunction

你可以在钩子中实现你的用例

You can implement your use case in hooks like

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

    useEffect(() => {
        if(!props.fetched) {
            props.fetchRules();
        }
        console.log('mount it!');
    }, []); // passing an empty array as second argument triggers the callback in useEffect only after the initial render thus replicating `componentDidMount` lifecycle behaviour

    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>  
    )
}

useEffect 还可以返回一个将在卸载组件时运行的函数.这可用于取消订阅侦听器,复制 componentWillUnmount 的行为:

useEffect can also return a function that will be run when the component is unmounted. This can be used to unsubscribe to listeners, replicating the behavior of componentWillUnmount:

例如:componentWillUnmount

useEffect(() => {
    window.addEventListener('unhandledRejection', handler);
    return () => {
       window.removeEventListener('unhandledRejection', handler);
    }
}, [])

要使 useEffect 以特定事件为条件,您可以为其提供一组值以检查更改:

To make useEffect conditional on specific events, you may provide it with an array of values to check for changes:

例如:componentDidUpdate

componentDidUpdate(prevProps, prevState) {
     const { counter } = this.props;
     if (this.props.counter !== prevState.counter) {
      // some action here
     }
}

Hook 等效

useEffect(() => {
     // action here
}, [props.counter]); // checks for changes in the values in this array

如果您包含此数组,请确保包含随时间变化的组件范围内的所有值(道具、状态),否则您最终可能会引用之前渲染中的值.

If you include this array, make sure to include all values from the component scope that change over time (props, state), or you may end up referencing values from previous renders.

使用 useEffect 有一些微妙之处;查看 API 此处.

There are some subtleties to using useEffect; check out the API Here.

v16.7.0 之前

函数组件的特性是它们无法访问 Reacts 生命周期函数或 this 关键字.如果你想使用生命周期函数,你需要扩展 React.Component 类.

The property of function components is that they don't have access to Reacts lifecycle functions or the this keyword. You need to extend the React.Component class if you want to use the lifecycle function.

class Grid extends React.Component  {
    constructor(props) {
       super(props)
    }

    componentDidMount () {
        if(!this.props.fetched) {
            this.props.fetchRules();
        }
        console.log('mount it!');
    }
    render() {
    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>  
    )
  }
}

当你只想渲染你的组件而不需要额外的逻辑时,函数组件很有用.

Function components are useful when you only want to render your Component without the need of extra logic.

这篇关于函数组件内的 ReactJS 生命周期方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆