简体   繁体   English

如何在功能组件中使用 componentDidMount() 执行 function

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

I have a functional component which had a button to call a method in it.我有一个功能组件,其中有一个按钮可以调用其中的方法。 Now i want to get rid of the button and call that method without any actions once the component loads.现在我想摆脱按钮并在组件加载后调用该方法而不执行任何操作。 I am making API calls inside this method and passing on the results to another component.我正在该方法中调用 API 并将结果传递给另一个组件。 Also I am replacing the button with a progress bar meaning when a "search" is taking place, display the progress bar but I am having no luck.此外,我正在用进度条替换按钮,这意味着在进行“搜索”时显示进度条,但我没有运气。 What am I doing wrong?我究竟做错了什么?

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>
    );
}

You will want to use the useEffect hook with an empty dependency array which will make it act as componentDidMount source .您将希望使用带有空依赖项数组的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.

相关问题 React - 如何从子功能组件执行功能 - React - How to execute function from child functional component 我如何调用/执行外部功能组件的 function 反应? - How can i call/execute function of functional component outside react? 再次单击组件时如何再次重新执行componentDidMount? - How to re execute componentDidMount again when i click the component again? 将有状态 React 组件转换为无状态功能组件:如何实现“componentDidMount”类型的功能? - Converting stateful React component to stateless functional component: How to implement "componentDidMount" kind of functionality? 如何导出功能组件 function? - How to export a functional component function? 如何在这个功能组件中使用 state? - How to use state in this functional component? Antd如何使用一种onLoad或componentDidMount function? - Antd how to use a kind of onLoad or componentDidMount function? 仅在调用者(某些回调)中更改 state 后,如何在 React 功能组件中没有 useEffect 的情况下执行 function? - How to execute the function only after state changed in the caller (some callback) without useEffect in React functional component? 如何测试componentDidMount时调用的组件function? - How to test a component function being called when componentDidMount? 函数在传递给功能组件时不执行 - Function Doesn't Execute When Passed to Functional Component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM