admin管理员组文章数量:1201640
I need to do a request when the page loaded (only once). I tried to do something like
if(!array.length){doRequest())
But with this method, react does more than 1 request, and I think that it will reduce my app speed. So I need the solution of this problem. Thanks
I need to do a request when the page loaded (only once). I tried to do something like
if(!array.length){doRequest())
But with this method, react does more than 1 request, and I think that it will reduce my app speed. So I need the solution of this problem. Thanks
Share Improve this question asked Jan 25, 2020 at 23:04 Alex KhanasAlex Khanas 3451 gold badge6 silver badges15 bronze badges2 Answers
Reset to default 14When working with Class Components, the solution would be to make that request in the componentDidMount lifecycle, which is only called once.
class Example extends React.Component {
componentDidMount() {
doRequest();
}
render() {
return null;
}
}
If you're trying to use Hooks in a functional component instead of Class components then you should use:
function Example() {
useEffect(() => doRequest(), []);
return null;
}
Hoping of course, that doRequest is declared in an upper scope or imported somehow.
Hope this solves your question, if you need more insight into this I found a great article about replacing lifecycle with hooks.
https://dev.to/trentyang/replace-lifecycle-with-hooks-in-react-3d4n
just use useEffect Hook
import React, {useEffect} from 'react'
const func = () => {
useEffect(()=> {
doRequest()
},[]) // empty array means it only run once
}
本文标签: javascriptHow to do request on page loadreact hooksStack Overflow
版权声明:本文标题:javascript - How to do request on page load, react hooks - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738635550a2104009.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论