gpt4 book ai didi

react-native - react-navigation:检测屏幕、标签栏何时被激活/出现/聚焦/模糊

转载 作者:行者123 更新时间:2023-12-03 09:01:41 26 4
gpt4 key购买 nike

以前当我想在屏幕打开时做一些 Action 时,我把它们放在 componentDidMount 里面.例如我可以获取一些数据。

像这样。

componentDidMount() {
this.updateData();
}

但与 react-navigation componentDidMount 仅在用户第一次打开屏幕时发生一次,如果以后用户再次打开该页面,则不会触发 componentDidMount。

检测页面(屏幕)何时被激活并执行操作的正确方法是什么?

最佳答案

react-navigation ,您可以分两步完成:

  • componentDidMount 添加监听器或 componentWillMount , Hook 事件
  • 删除 componentWillUnmount 中的监听器, 避免意外调用

  • API 引用文档 v3.x、v4.x、v5.x:
    react 导航 v3.x, v4.x :

    addListener - Subscribe to updates to navigation lifecycle

    React Navigation emits events to screen components that subscribe tothem:

    • willFocus - the screen will focus
    • didFocus - the screen focused (if there was a transition, the transition completed)
    • willBlur - the screen will be unfocused
    • didBlur - the screen unfocused (if there was a transition, the transition completed)

    react 导航 3.x、4.x 例子:
    const didBlurSubscription = this.props.navigation.addListener(
    'didBlur',
    payload => {
    console.debug('didBlur', payload);
    }
    );

    // Remove the listener when you are done
    didBlurSubscription.remove();
    引用 v4.x https://reactnavigation.org/docs/4.x/navigation-prop/#addlistener---subscribe-to-updates-to-navigation-lifecycle
    更新 v5.x
    事件已在 v5.x 中更改

    Screens can add listeners on thenavigation prop like in React Navigation. By default, there are 2events available:

    • focus - This event is emitted when the screen comes into focus
    • blur - This event is emitted when the screen goes out of focus
    • state (advanced) - This event is emitted when the navigator's state changes

    来自 reactnavigation.org 的示例代码
    class Profile extends React.Component {
    componentDidMount() {
    this._unsubscribe = navigation.addListener('focus', () => {
    // do something
    });
    }

    componentWillUnmount() {
    this._unsubscribe();
    }

    render() {
    // Content of the component
    }
    }
    与 Hook 使用
    function Profile({ navigation }) {
    React.useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
    // do something
    });

    return unsubscribe;
    }, [navigation]);

    return <ProfileContent />;
    }
    屏幕上的听众 Prop
    <Tab.Screen
    name="Chat"
    component={Chat}
    listeners={({ navigation, route }) => ({
    tabPress: e => {
    // Prevent default action
    e.preventDefault();

    // Do something with the `navigation` object
    navigation.navigate('AnotherPlace');
    },
    })}
    />
    引用 v5.x: https://reactnavigation.org/docs/navigation-events

    关于react-native - react-navigation:检测屏幕、标签栏何时被激活/出现/聚焦/模糊,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50290818/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com