如何在函数式组件中使用 componentDidMount() 来执行一个函数

How to Use componentDidMount() in Functional Component to execute a function

我有一个功能组件,其中有一个调用方法的按钮。现在我想摆脱按钮并在组件加载后调用该方法而不执行任何操作。 我正在此方法内部进行 API 调用,并将结果传递给另一个组件。 此外,我正在用进度条替换按钮,这意味着在进行“搜索”时显示进度条,但我没有运气。我做错了什么?

export const Search = (props) => {

    const { contacts, setContacts, onSearchComplete } = props;

    const [msgBox, setMsgBox] = useState(null);
    const [loading, setLoading] = useState(false);

    const onSearch = async () => {

        setLoading(true);

        const emails = contacts
            .filter(x => x.isChecked)
            .map(item => item.emailAddress);

        try {
            const searchResults = await AppApi.searchMany(emails);

            let userList = [];
            for (let i = 0; i < searchResults.length; i++) {
               //process the list and filter
                }
                userList = [...userList, ..._users];
            }

            onSearchComplete(userList); //passing the results. 
        } catch (err) {
            console.log({ err });
            setMsgBox({ message: `${err.message}`, type: 'error' });
        }

        setLoading(false);
    }


    return (
        <Box>
        
            {loading ? <LinearProgress /> : <Box>{msgBox && (<a style={{ cursor: 'pointer' }} onClick={() => setMsgBox(null)} title="Click  to dismiss"><MessageBox type={msgBox.type || 'info'}>{msgBox.message}</MessageBox></a>)}</Box>}

            /*{onSearch()}*/ // function that was executed onclick. 

        </Box>
    );
}

您将要使用 useEffect hook with an empty dependency array which will make it act as componentDidMount


export const Search = (props) => {

    const { contacts, setContacts, onSearchComplete } = props;

    const [msgBox, setMsgBox] = useState(null);
    const [loading, setLoading] = useState(false);

    const onSearch = async () => {
      ...
    }

    useEffect(() => {
      onSearch();
    }, []);


    return (
        <Box>      
            {loading ? <LinearProgress /> : <Box>{msgBox && (<a style={{ cursor: 'pointer' }} onClick={() => setMsgBox(null)} title="Click  to dismiss"><MessageBox type={msgBox.type || 'info'}>{msgBox.message}</MessageBox></a>)}</Box>}
        </Box>
    );
}