【问题标题】:useEffect does not get triggered when getting redirected from another page using Ionic使用 Ionic 从另一个页面重定向时不会触发 useEffect
【发布时间】:2022-01-14 10:39:40
【问题描述】:

这是使用离子和反应。

从 PageB 返回时,我正在尝试刷新 PageA 上的数据。但是,从 PageB 重定向后,如果不对 PageA 进行硬刷新,这是行不通的。

我正在使用 useEffect 获取数据

//empty array in use state means it will runs once after the component is loaded
  useEffect(() => {
    console.log(process.env)
    fetch(`${process.env.REACT_APP_API_URL}/invoicems/receipt`)
      .then(res => res.json())
      .then(result => {
        setIsLoaded(true)
        setItems(result)
        console.log(result)

      }, (error) => {
        setIsLoaded(true)
        setError(error)
      })
  }, [])

数据被正确提取并正确显示。同一页面上有一个添加按钮。代码如下

  <IonFab vertical="bottom" horizontal="end" slot="fixed">
    <IonFabButton routerLink="/add-receipt">
      <IonIcon icon={add}></IonIcon>
    </IonFabButton>
  </IonFab>

正确的重定向到添加收据页面。该页面具有数据输入以创建数据。添加数据后,我使用此代码重定向到上述页面。

const saveHandler=()=>{
        const receipt={
            "ReceiptDate": receiptDate.current!.value,
            "Amount":amount.current!.value,
            "MerchantId":selectedMerchant,
            "ReceiptData":receiptImage?.base64,
            "Description":description.current!.value   
        }
        console.log(receipt)
        const requestOptions = {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(receipt)
        };
        fetch(`${process.env.REACT_APP_API_URL}/invoicems/receipt`, requestOptions)
            .then(async (response) => {
                if (!response.ok) {
                    var error = await response.json();
                    throw Error(JSON.stringify(error))
                }else{
                    history.length>0? history.goBack() : history.replace('home')
                } 

            })
            .catch(error => {
               console.log(error);
            });
    }

问题是第一页上的数据没有刷新就不会刷新。如何解决这个问题?

【问题讨论】:

    标签: reactjs ionic-framework react-hooks


    【解决方案1】:

    问题出在 history.goBack() 中。该方法不会调用您的 useEffect,因为它尚未卸载然后安装,该页面一直都在那里。

    我建议使用另一种方法,例如 history.go() 或另一种不会破坏您的历史日志的方法。

    另一种可能性是使用 useEffect 但将历史记录作为依赖项,而不是 []。这样,例如,只要历史记录与您的路径匹配,您就可以触发该提取。您可以使用 useHistory 钩子获取历史记录。

    【讨论】:

    • 谢谢罗伯特。我通过使用 history.go() 尝试了您的建议,但没有奏效。再次感谢您的回答。
    【解决方案2】:

    通过执行以下操作找到了解决此问题的方法。每次在页面之间切换时,[location.key] 都会发生变化。因此,在这种情况下需要使用它作为依赖项。从 https://dev.to/zbmarius/react-route-refresh-without-page-reload-1907

    Adam Rich 在 cmets 部分提到过

    import { useLocation } from 'react-router';
    
    const location = useLocation();
    
     const location = useLocation();
      useEffect(() => {
        console.log(location.key)
        getData();
      },[location.key])
    

    【讨论】:

      猜你喜欢
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      • 2014-09-01
      • 2020-04-12
      • 2017-08-03
      • 2021-12-22
      相关资源
      最近更新 更多