以前当我想在屏幕打开时做一些 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 lifecycleReact Navigation emits events to screen components that subscribe to them:
willFocus
- the screen will focusdidFocus
- the screen focused (if there was a transition, the transition completed)willBlur
- the screen will be unfocuseddidBlur
- 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 the navigation prop like in React Navigation. By default, there are 2 events 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/