导航到同一屏幕时未调用 EXPO useEffect
EXPO useEffect not called on navigating to same screen
我有一个屏幕在流程中第一次呈现时调用了 useEffect。
我第二次导航到流程中的屏幕时,未调用使用效果但我想在我们第二次导航到同一屏幕时调用渲染函数之前、之后或期间第一次调用函数。
这是每次从各种屏幕导航到此屏幕时的导航调用
navigation.navigate("x", { u:type, s:title});
以下是我的屏幕结构。我没有使用组件,而是使用导航功能
const x = ({ navigation}) => {
...
return (
<View style={styles.a}>
...
</View>
);
};
export default x;
useEffect
将在您的功能组件首次加载时或某些依赖项将被更改时调用。一切都保持不变,所以你的 useEffect
将不起作用。考虑改用 react-navigation
库中的 useFocusEffect
。
这里的问题是初始导航后的屏幕 remains mounted in react-native
。因此,具有空依赖项数组的 useEffect
将不会在随后的导航中被调用。
注意 this behavior differs from the web.
If you are coming to react-navigation from a web background, you may assume that when user navigates from route A to route B, A will unmount (its componentWillUnmount is called) and A will mount again when user comes back to it. While these React lifecycle methods are still valid and are used in react-navigation, their usage differs from the web.
recommended way to solve this is described here。对于您的情况,可以按如下方式解决。
import { useFocusEffect } from '@react-navigation/native';
const x = ({ navigation}) => {
useFocusEffect(
React.useCallback(() => {
// called when screen is focused, thus everytime on navigation
return () => {
// unfocus... cleanup ... or whatever
};
}, [])
);
...
return (
<View style={styles.a}>
...
</View>
);
};
export default x;
我有一个屏幕在流程中第一次呈现时调用了 useEffect。 我第二次导航到流程中的屏幕时,未调用使用效果但我想在我们第二次导航到同一屏幕时调用渲染函数之前、之后或期间第一次调用函数。
这是每次从各种屏幕导航到此屏幕时的导航调用
navigation.navigate("x", { u:type, s:title});
以下是我的屏幕结构。我没有使用组件,而是使用导航功能
const x = ({ navigation}) => {
...
return (
<View style={styles.a}>
...
</View>
);
};
export default x;
useEffect
将在您的功能组件首次加载时或某些依赖项将被更改时调用。一切都保持不变,所以你的 useEffect
将不起作用。考虑改用 react-navigation
库中的 useFocusEffect
。
这里的问题是初始导航后的屏幕 remains mounted in react-native
。因此,具有空依赖项数组的 useEffect
将不会在随后的导航中被调用。
注意 this behavior differs from the web.
If you are coming to react-navigation from a web background, you may assume that when user navigates from route A to route B, A will unmount (its componentWillUnmount is called) and A will mount again when user comes back to it. While these React lifecycle methods are still valid and are used in react-navigation, their usage differs from the web.
recommended way to solve this is described here。对于您的情况,可以按如下方式解决。
import { useFocusEffect } from '@react-navigation/native';
const x = ({ navigation}) => {
useFocusEffect(
React.useCallback(() => {
// called when screen is focused, thus everytime on navigation
return () => {
// unfocus... cleanup ... or whatever
};
}, [])
);
...
return (
<View style={styles.a}>
...
</View>
);
};
export default x;