React Query的.isSuccess在我使用axios进行get请求时发生错误
P粉153503989
P粉153503989 2023-08-15 23:34:15
[React讨论组]
<p><br /></p> <pre class="brush:php;toolbar:false;">const searchInvoiceList = async ( plantLoc: string, invoiceOption: string ) =&gt; { let data: InvoiceData[] = []; await axios .get(`${linkURL}inv/getControlList/${plantLoc}/${invoiceOption}`) .then((response) =&gt; { data = response.data.sqlData; }) .catch((error) =&gt; console.error(error)); return data; }; const fetchInvoices = useQuery({ queryKey: [ "invoiceData", plantLocationOptionChecked.value, invoiceOptionChecked.value, ], queryFn: () =&gt; searchInvoiceList( plantLocationOptionChecked.value, invoiceOptionChecked.value ), enabled: false, retry: 0, }); if (fetchInvoices.isSuccess) { if (fetchInvoices.data.length === 0) { toast.error("搜索结果为空"); } setFetchedInvoiceData(fetchInvoices.data); } if (fetchInvoices.isError) { console.log(fetchInvoices.error); }</pre> <p>我有一个按钮,有一个onClick事件,调用fetchInvoices.refetch()时出现错误。第一个错误是“重新渲染次数过多。React限制了渲染次数以防止无限循环。”如果我去掉<code>setFetchedInvoiceData(fetchInvoices.data);</code>并且数组返回为0,它会触发我的react-hot-toast函数<code>toast.error("搜索结果为空");</code>但然后我会收到警告“在渲染不同组件(<code>App</code>)时无法更新组件(<code>Ie</code>)”。我做错了什么,如何修复这个问题?</p>
P粉153503989
P粉153503989

全部回复(1)
P粉517090748

在没有查看您整个组件的代码的情况下,很难为您提供最佳解决方案,但是目前在这里我看到您在每次重新渲染时都在fetchInvoices.isSuccess上运行条件,解决的最佳方法是将其添加到useEffect中,如下所示:

useEffect(() => {
      if (fetchInvoices.isSuccess) {
        if (fetchInvoices.data.length === 0) {
          toast.error("搜索结果为空");
        }
        setFetchedInvoiceData(fetchInvoices.data);
      }
     if (fetchInvoices.isError) {
       console.log(fetchInvoices.error);
     }
   }, [fetchInvoices.isSuccess, fetchInvoices.isError])
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号