从抽屉打开时刷新组件(反应导航)

Refresh component on open from drawer (react navigation)

编辑:异步调用现在已放置在 axios.all() 调用中以加快进程。问题依旧。

在我的应用程序中,当在登录屏幕上按注销时,存储在设备上的令牌将被删除。

Login.js:

    async resetKey() {
        try {
            await AsyncStorage.removeItem('@MySuperStore:key');
            this.setState({
                token: null,
                loggedIn: false,
            });
        } catch (error) {
            this.setState({
                token: null,
                loggedIn: false,
            });
        }
    }

现在我想在另一个页面中使用这个事实,在那里我将渲染基于道具 loggedIn。如果已登录,那么 true,我将呈现活动和一个绿色或红色框,指示用户是否已注册 activity。这一切都相当微不足道,并且工作正常:

    if (this.state.loggedIn) {
        return (
            <ScrollView refreshControl={
                <RefreshControl refreshing={this.state.refreshing} onRefresh={this.onRefresh.bind(this)} />
            }>
                <Loader loading={this.state.loading} />

                <Text style={styles.foodHeader}>Activiteiten</Text>
                {this.state.activities.map((activity) => (
                    <TouchableOpacity key={activity.id} onPress={() => this.onOpenActivity(activity)} style={styles.foodActivityField}>
                        <Text>{`${activity.name}`}</Text>
                        <View>
                            {this.showRegistered(activity.id) ? registered : notRegistered}
                        </View>
                    </TouchableOpacity>
                ))}

                <Text style={styles.foodHeader}>Eten</Text>
                {this.state.foods.map((food) => (
                    <TouchableOpacity key={food.id} onPress={() => this.onOpenFood(food)} style={styles.foodActivityField}>
                        <Text>{`${food.name}`}</Text>
                        <View>
                            {this.showRegistered(food.id) ? registered : notRegistered}
                        </View>
                    </TouchableOpacity>
                ))}

            </ScrollView>
        );
    }

但是,当用户刚刚注销时不应显示此内容。在这种情况下,它应该显示一个简单的文本 'You have to be logged in to view activities'.

    else {
        {/** User is not logged in */ }
        return (
            <ScrollView refreshControl={
                <RefreshControl refreshing={this.state.refreshing} onRefresh={this.onRefresh.bind(this)}  />
            }>
                <Loader loading={this.state.loading} />
                <Text>You have to be logged in to view activities</Text>
            </ScrollView>
        );
    }

为简单起见,registerednotRegistered 以及 onOpenFoodonOpenActivity 函数的渲染已被省略。对于刷新功能和 API 调用工作,我有这段代码(API 调用的功能在单独的文件中,这些是基本的 axios 请求,都 GETPOST) :

constructor(props) {
    super(props);
    this.state = {
        loading: true,
        refreshing: false,
        activities: [],
        foods: [],
        registered: []
    }
    this.getData
}

/* Handles the action necessary to refresh */
onRefresh = () => {
    this.setState({ refreshing: true });
    this.getData().then(() => {
        this.setState({ refreshing: false });
    });
}

async componentDidMount() {
    // Do the necessary API calls
    this.getData();
}

getData = async () => {

    this.setState({loading: true})
    /* Get token from storage */
    try {
        console.log('trying to get key...')
        const value = await AsyncStorage.getItem('@MySuperStore:key');
        if (value) {
            this.setState({
                token: value,
                loggedIn: true
            });

            /* Retrieve activities */
            const activities = await getActivities();
            this.setState({ activities });

            /* Retrieve food */
            const foods = await getFood();
            this.setState({ foods });

            /* Retrieve the activity ID's the user is registered for */
            const registered = await getRegistered(this.state.token);
            this.setState({ registered });
            this.setState({ loading: false })

        } else {
            this.setState({
                token: null,
                loggedIn: false,
                loading: false
            });
        }
    } catch (error) {
        this.setState({
            token: null,
            loggedIn: false
        });
        console.log("help")
    }


}

现在的问题是重新打开页面时没有看到this.state.registered的变化,导致页面显示不正确。刷新页面有效,因为整个状态都已重置。这怎么能解决?有没有办法在再次加载页面时调用 onRefresh ?该页面以及函数 onOpenFoodonOpenActivity 导航到的页面是 StackNavigator 的一部分,它本身是 DrawerNavigator (react-navigation 3.3.2) 的一部分。

万一有人无意中发现了这个问题,您可能需要查看类似 useEffect 挂钩和侦听器的东西。在这种情况下,它看起来像这样;

useEffect(()=> {
  const unsubscribe = navigation.addListener('focus', () => {
    onRefresh();
  });

  return unsubscribe;
}, [navigation]);

这确保在页面上的焦点返回时调用 onRefresh 函数,并且在导航道具中的某些内容发生更改时调用 onRefresh 函数。这是一个老问题,所以我没有在代码中修改它,但在较新的项目中,这似乎工作得很好