How to have useEffect() act like componentDidMount()?
我正在使用一个功能组件,我需要能够使用 componentDidMount()。网上发现通过react hooks可以在功能组件中使用useEffect()作为componentDidMount()。但是,这并没有像我想象的那样工作。我在想在页面加载时这会触发,但事实并非如此。有谁知道如何让 useEffect 像 componentDidMount 一样工作?
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
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 |
我只是简单地尝试这样做,但它会创建一个无限循环并且我得到一个错误:
1
2 3 |
useEffect(() => {
sendEnhancedTrackEvent(enhanceableData); }); |
是的,我已经导入了它:
1
|
import React, { useState, useEffect } from ‘react’;
|
- 你实际上并没有在你的 useEffect() 中做任何事情,你只是立即清理。您是否尝试过在那里记录一些东西?
1
2 3 4 5 6 |
const ProvidersContainer = ({getProvidersData}) => {
const [pageNo, setpageNo] = useState(1); useEffect(() => { // Component Did Mount getProvidersData(pageNo); }, []); } |
useEffect 的工作方式有点不同。
它接收一个函数,该函数可以返回一个清理函数。
所以你的代码可能是:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
const Contact = ({
previousProgressBarNow, setPreviousStepValue, addPropsToCallback, hasSuggestions, showSMSOptInCheckbox, params, sendEnhancedTrackEvent }) => { // code // This acts as componentDidMount |
来源:https://www.codenong.com/55753657/