如何使用useEffect()就像componentDidMount()?

问题描述 投票:0回答:2

我正在使用功能组件,我需要能够使用componentDidMount()。在线我发现通过反应挂钩你可以在功能组件中使用useEffect()作为componentDidMount()。但是,这不符合我的想法。我认为在页面加载时会发生这种情况,但事实并非如此。有谁知道如何让useEffect像componentDidMount一样行事?

const Contact = ({
  previousProgressBarNow,
  setPreviousStepValue,
  addPropsToCallback,
  hasSuggestions,
  showSMSOptInCheckbox,
  params,
  sendEnhancedTrackEvent
}) => {
  const enhanceableData = {
    name: 'Item Clicked',
    properties: {
      ...defaultProps,
      activityLocation: 'Member - RAQ Contact Details - useEffect',
      description: 'SMS Opt-In Checkbox',
      autopopulated: true,
      changeType: 'Add',
      href: process.env.IS_BROWSER && typeof window !== 'undefined' ?
          window.location.href : undefined
    }
  };

  // This acts as componentDidMount
  useEffect(() => {
    return () => {
      sendEnhancedTrackEvent(enhanceableData);
    }
  }, []);

我只是尝试这样做,但它创建了一个无限循环,我得到一个错误:

  useEffect(() => {
    sendEnhancedTrackEvent(enhanceableData);
  });

是的,我已导入它:

import React, { useState, useEffect } from 'react';
javascript reactjs react-hooks
2个回答
1
投票

useEffect有点不同。它接收一个可以返回清理功能的函数。

所以你的代码可能是:

const Contact = ({
  previousProgressBarNow,
  setPreviousStepValue,
  addPropsToCallback,
  hasSuggestions,
  showSMSOptInCheckbox,
  params,
  sendEnhancedTrackEvent
}) => {
  // code

  // This acts as componentDidMount
  useEffect(() => {
    sendEnhancedTrackEvent(enhanceableData);
  }, []);

1
投票
const ProvidersContainer = ({getProvidersData}) => {
 const [pageNo, setpageNo] = useState(1);
 useEffect(() => { // Component Did Mount
  getProvidersData(pageNo);
 }, []);
}
© www.soinside.com 2019 - 2024. All rights reserved.