繁体   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