Skip to content
This repository was archived by the owner on Feb 25, 2020. It is now read-only.

Fix NavigationEvents implementation #17

Merged
merged 1 commit into from
Nov 9, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 15 additions & 28 deletions src/views/NavigationEvents.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,43 +11,30 @@ const EventNameToPropName = {
const EventNames = Object.keys(EventNameToPropName);

class NavigationEvents extends React.Component {
getPropListener = eventName => this.props[EventNameToPropName[eventName]];

componentDidMount() {
this.subscriptions = {};
EventNames.forEach(this.addListener);
}

componentDidUpdate(prevProps) {
// We register all navigation listeners on mount to ensure listener stability across re-render
// A former implementation was replacing (removing/adding) listeners on all update (if prop provided)
// but there were issues (see https://github.com/react-navigation/react-navigation/issues/5058)
EventNames.forEach(eventName => {
const listenerHasChanged =
this.props[EventNameToPropName[eventName]] !==
prevProps[EventNameToPropName[eventName]];
if (listenerHasChanged) {
this.removeListener(eventName);
this.addListener(eventName);
}
});
}

componentWillUnmount() {
EventNames.forEach(this.removeListener);
}

addListener = eventName => {
const listener = this.props[EventNameToPropName[eventName]];
if (listener) {
this.subscriptions[eventName] = this.props.navigation.addListener(
eventName,
listener
(...args) => {
const propListener = this.getPropListener(eventName);
return propListener && propListener(...args);
}
);
}
};
});
}

removeListener = eventName => {
if (this.subscriptions[eventName]) {
componentWillUnmount() {
EventNames.forEach(eventName => {
this.subscriptions[eventName].remove();
this.subscriptions[eventName] = undefined;
}
};
});
}

render() {
return null;
Expand Down
Loading