在 React Native 中使用 withNavigationFocus 的内存泄漏问题
Memory leak problem using withNavigationFocus in React Native
我使用 withNavigationFocus
设置了一个侦听器,这样每次用户到达屏幕或离开屏幕时,都会触发特定事件。但是,我收到以下错误:
Warning: Can't perform a React state update on an unmounted component.
This is a no-op, but it indicates a memory leak in your application.
To fix, cancel all subscriptions and asynchronous tasks
const PleaseSignIn = props => {
const {
state: { authOpen },
authModal
} = useContext(Context)
const focusListener = props.navigation.addListener('didFocus', () => {
retrieveToken()
})
const retrieveToken = async () => {
try {
const token = await AsyncStorage.getItem(LOGIN_TOKEN)
if(!token) {
authModal()
}
} catch (err) {
throw new Error(err)
}
}
if(!authOpen) {
return (
<View style={styles.container}>
<Auth navigation={props.navigation} />
<Signup navigation={props.navigation} />
<Signin navigation={props.navigation} />
</View>
)
}
return props.children
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}
})
export default withNavigationFocus(PleaseSignIn)
设置事件监听器后,我们还必须在卸载屏幕时停止监听事件。
你有功能组件,可以使用钩子订阅和取消订阅。
像这样:
useEffect(() => {
const focusListener =
props.navigation.addListener('didFocus', async() => {
await retrieveToken();
});
// returned function will be called on component
//unmount
return () => {
focusListener.remove();
}
}, []);
我使用 withNavigationFocus
设置了一个侦听器,这样每次用户到达屏幕或离开屏幕时,都会触发特定事件。但是,我收到以下错误:
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks
const PleaseSignIn = props => {
const {
state: { authOpen },
authModal
} = useContext(Context)
const focusListener = props.navigation.addListener('didFocus', () => {
retrieveToken()
})
const retrieveToken = async () => {
try {
const token = await AsyncStorage.getItem(LOGIN_TOKEN)
if(!token) {
authModal()
}
} catch (err) {
throw new Error(err)
}
}
if(!authOpen) {
return (
<View style={styles.container}>
<Auth navigation={props.navigation} />
<Signup navigation={props.navigation} />
<Signin navigation={props.navigation} />
</View>
)
}
return props.children
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}
})
export default withNavigationFocus(PleaseSignIn)
设置事件监听器后,我们还必须在卸载屏幕时停止监听事件。 你有功能组件,可以使用钩子订阅和取消订阅。 像这样:
useEffect(() => {
const focusListener =
props.navigation.addListener('didFocus', async() => {
await retrieveToken();
});
// returned function will be called on component
//unmount
return () => {
focusListener.remove();
}
}, []);