![](/img/trans.png)
[英]How to make useEffect only run once on component mount without lying to React?
[英]How to run useEffect on component mount as well as state changes
I have a useEffect function which runs only when the page state changes, but I want to run this function on both component mount as well as state change.
为此,我在依赖数组中使用了两个变量
, [页, []]
在依赖数组中使用这个表达式会在控制台中显示一个警告,并且 useEffect 方法会无限运行,我不知道如何解决这个问题。
我的 useEffect 功能是
// fetch data from the server when page changes useEffect(() => { axios.get(fetchURL, { headers: { Authorization: AuthStr } }).then((response) => { // If request is good... if (response) { setData(response.data); } }).catch((error) => { toast.error('Something went wrong, please refresh'); console.log(error); }); // eslint-disable-next-line react-hooks/exhaustive-deps }, [page]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
请提出一个可能的解决方案来解决这个问题。
您的代码将在挂载后运行,以及您在依赖数组中传递的“页面”值是否有任何变化。 在“页面”中执行一些更改,您会看到它会重新渲染。 如果您使用其他一些实体来推断 state 发生变化,则您也应该将其包含在依赖数组中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.