[英]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.