【问题标题】:React Native refresh content when user hits back button - using Hooks当用户点击返回按钮时反应原生刷新内容 - 使用 Hooks
【发布时间】:2020-01-27 17:12:41
【问题描述】:

当用户从一个页面返回到另一个页面时,我想刷新数据。 这就是我的 useEffect 函数现在的样子:

useEffect(() => {
    setIsLoading(true);

    AsyncStorage.getItem("user").then((response) => {
        const currentData = JSON.parse(response);
        setUser(currentData)
        fetch('URL',
            {
                method: 'POST',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    user_id: currentData.id
                }),
            }
        )
            .then(response => response.json())
            .then(data => {
                 setNotis(data.notifications);
                 setIsLoading(false)
            })
            .catch(error => {
            });
    });
}, []);

当用户在页面上时,这个函数应该运行。不管是不是 onBackPressed。

谢谢

【问题讨论】:

  • 向您的useEffect 调用添加一个依赖项,当您单击返回按钮时该调用会发生变化。不确定在 React Native 中会是什么,但如果您使用某些东西进行路由,它将是存储路由的状态。
  • @Alex W 是否可以将 isLoading 添加为依赖项(没有无限循环)?
  • 不在 useEffect 调用中时
  • 您能否使用提供的代码示例为我提供一个工作示例?
  • 试试这个:medium.com/@Farzad_YZ/…

标签: reactjs react-native mobile react-hooks


【解决方案1】:

使用反应导航

如果您使用 react-navigation

,我们可以直接刷新屏幕

导入@react-navigation/native

import React, { useEffect } from "react";
import { useIsFocused } from "@react-navigation/native";

const HomeScreen = (props) => {
const isVisible = useIsFocused();

useEffect(() => {
    console.log("called when screen open and also on close"); 
    // this will call on both screen open and screen close.

   if (isVisible) {
      console.log("called when screen open or when back on screen "); 
   }

}, [isVisible]);

return (
    ......
)

}

我希望它会有所帮助。

【讨论】:

    【解决方案2】:

    这里真正的问题是在屏幕之外导航时没有卸载屏幕,因此钩子不会触发,因为组件已经安装。有多种选项可以解决此问题,就像在屏幕聚焦/模糊时添加侦听器一样,或者只是观察 navigation 道具的变化。对于最后一种解决方法,您可以尝试以下方法:

    useEffect(() => {
        setIsLoading(true);
    
        AsyncStorage.getItem("user").then((response) => {
            const currentData = JSON.parse(response);
            setUser(currentData)
            fetch('URL',
                {
                    method: 'POST',
                    headers: {
                        Accept: 'application/json',
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        user_id: currentData.id
                    }),
                }
            )
                .then(response => response.json())
                .then(data => {
                     setNotis(data.notifications);
                     setIsLoading(false)
                })
                .catch(error => {
                });
        });
    }, [navigation]);
    

    要观看 onFocus 事件,您可以从 react-navigation 导入 NavigationEvents 并将钩子的逻辑移动到函数 refreshData

    import {NavigationEvents} from 'react-navigation`
    ...
    
    <NavigationEvents onWillFocus={refreshData}/>
    
    

    此外,您应该在 Promise 完成时将 isLoading 状态设置为 false,例如,您可以使用

    .finally(() => {
      setIsLoading(false)
    })
    

    【讨论】:

    • 感谢使用 finally 函数的建议,但是当我尝试使用“导航”作为 useEffect 依赖项时,该函数尚未被调用。我还阅读了有关 NavigationEvents 的信息 (reactnavigation.org/docs/en/navigation-events.html)不过好像有点奇怪
    • @csirkeautomata 您能否更新您的问题并显示父级和屏幕及其道具?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多