我有一个屏幕,它调用api来获取一些数据,然后显示这些数据。
我看到的一个问题是,当我离开屏幕导航(我使用的是react导航6.x),然后返回到它时,useEffect()是不被调用的。
从我到目前为止所读到的,这是由于userId没有改变的价值(我认为我需要更多地阅读useEffect()钩子,以便更好地理解,也许有人会帮助澄清这个问题)
import React, {useState, useEffect, useContext} from 'react';
import AppContext from '../../components/AppContext.js';
export const CreateNewEvent = () => {
const globalContext = useContext(AppContext);
const userId = globalContext.userInfo.id;
useEffect(() => {
const body = JSON.stringify({userId});
fetch(eventTypesUrl, {
method: 'POST',
headers: {'Content-Type': 'application/json', Accept: 'application/json'},
body: body,
})
.then(response => response.json())
.then(json => setEventTypeData(json))
.catch(error => console.error(error))
.finally(() => setLoading(false));
}, [userId]);
}因此,在我的场景中,我在屏幕1上(在这里,我可以创建一个请求获取所有事件类型并将它们加载到选择菜单中的事件)。
当我导航到屏幕2(创建一个事件类型),然后返回到屏幕1时,不会调用useEffect()钩子,导致无法看到我刚才创建的事件类型(希望这是有意义的)。还请注意,以前在屏幕1中输入的任何数据仍然保持不变。
我遇到了这个post,它似乎是我正在处理的,只是有点不确定如何用我的设置来实现。
当我返回时,如何确保屏幕2发出api调用,并清除所有以前的表单数据?
谢谢
发布于 2022-01-07 14:44:15
在核心部分,当用户导航回屏幕以进行性能优化时,不会重新调整屏幕,并避免不必要的更改程序。
当需要时,它们提供了一个有用的钩子来检测屏幕何时聚焦并运行一些副作用。
让重构代码如下所示:
Top-level import
import { useFocusEffect } from "@react-navigation/core";
// Run side effects when screen focused, navigated, or visited
useFocusEffect(
React.useCallback(() => {
const body = JSON.stringify({userId});
fetch(eventTypesUrl, {
method: 'POST',
headers: {'Content-Type': 'application/json', Accept: 'application/json'},
body: body,
})
.then(response => response.json())
.then(json => setEventTypeData(json))
.catch(error => console.error(error))
.finally(() => setLoading(false));
return () => {
// Run somelogisx when user leave screen,
// Cleaning caches or cancelling subscriptions
};
}, [userId]))注意: React.useCallback是useFocusEffect API的一部分。试图通过回忆录优化屏幕性能。
发布于 2022-01-07 14:50:30
在React本机中,当您向前导航时,每个屏幕都被推送到导航堆栈。
现在,当您向后导航时,会弹出前一个屏幕,并显示堆栈中最顶层的屏幕。因为在最上面的屏幕上没有任何改变(状态或道具),它将不会被重新呈现。
所以你得做些体力活。
import { useIsFocused } from "@react-navigation/native";
const isFocused = useIsFocused();isFocused是布尔型的
useEffect(() => {
if (userId && isFocused) {
// Code which you want to execute when screen is loaded first
// time(and after userId is initialised) or loaded after press of
// back button
}
}, [userId, isFocused]);https://stackoverflow.com/questions/70622599
复制相似问题