簡體   English   中英

如何在功能組件中使用 componentDidMount() 執行 function

[英]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掛鈎,這將使其充當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>
    );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM