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

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

推荐答案

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

钩子是一个新的特性建议,允许您使用状态和其他

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

基本语法:

useEffect(callbackFunction, [dependentProps]) => cleanupFunction

您可以在钩子中实现您的用例,比如

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的行为:

Eg: componentWillUnmount

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

要使useEffect以特定事件为条件,可以为其提供一个值数组以判断更改:

Eg: componentDidUpdate

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

挂钩当量

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

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

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


Before v16.7.0

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

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

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

Reactjs相关问答推荐

从`redux—thunk`导入thunk `在stackblitz中不起作用

为什么这个'Suspense'子组件在挂起promise解决后会丢失它的状态,而不是呈现?<>

如何在MUI X数据网格列中显示IMG?

TypeError:SearchProduct.get()获得了意外的关键字参数查询'

如何在单击行中的图标时避免选中ionic 复选框?

使用REACT-RUTER-DOM链接仅更新一个搜索参数

如何使用TouchStart/TouchEnd在Table ReactJS中交换位置?

使用以Jest 的方式返回 Promise 的方法来模拟可构造的 API 类时出现问题

在React中使用if条件时如何更改Tailwind中元素的文本 colored颜色

Mui / Material UI 5:如何从 StaticTimePicker 中删除打开下一个视图/打开上一个视图按钮?

画布:用鼠标绘制形状时重新绘制整个画布会导致卡顿

无法在react 中向表中添加行

将水平滚动视图添加到底部导航选项卡

使用 nextjs App Router 在动态客户端进行服务器端渲染

图像路径很奇怪,部署 Next.js 应用程序后我看不到任何图像

React + i18next + Trans + Prettier:Prettier 最终会在重新格式化 JSX 时 destruct 翻译

如何将值从下拉列表传递到 select 上的输入?响应式JS

具有自动完成功能的 Formik material ui 无法按预期工作

运行开发服务器时如何为 Vite 指定运行时目录

添加禁用的默认选项以 Select