Reputation: 1314
I've created a component with a few functions for React components that I'd like to use in multiple components.
I've tried implementing it, but whenever I try to call super.updateHeader
, it crashes with error
ExceptionsManager.js:84 Unhandled JS Exception: TypeError: TypeError:
Cannot read property 'call' of undefined
Using super
in the constructor works without an issue.
Trying to reach the function with this.updateHeader
results in
Unhandled JS Exception: TypeError: TypeError: this.updateHeader is not a function
Neither updateHeader
nor the function I'm calling it from are arrow functions.
How do I solve this? (They're instance based, so I'd like to stay away from creating some sort of library for this)
SuperComponent:
class CustomRouteViewComponent extends Component {
updateHeader(props) {
const {settings, navigation} = props;
props.navigation.setParams({
headerTintColor: settings.theme === 'dark' ? commonColorDark.textColor : commonColor.textColor,
backgroundColor: settings.theme === 'dark' ? commonColorDark.headerStyle : commonColor.headerStyle,
});
};
}
const mapStateToProps = state => ({settings: state.settings});
export default connect(mapStateToProps)(CustomRouteViewComponent);
HomeScreen
class Home extends CustomRouteViewComponent {
componentWillMount() {
this.updateHeader(this.props);
}
render() {
return (
<View><Text>Hello!</Text></View>
)
}
}
const mapStateToProps = state => ({});
export default connect(mapStateToProps)(Home);
Upvotes: 0
Views: 159
Reputation: 223054
The problem is that OOP inheritance is mixed with functional approach (Redux connect
). CustomRouteViewComponent
in Home
module is connected functional component and not original class component.
CustomRouteViewComponent
class could be exported for inheritance purposes, or original class could be reached on connected component as:
class Home extends CustomRouteViewComponent.WrappedComponent {...}
This will result in problems because CustomRouteViewComponent
already relies on connected props, but its own mapStateToProps
won't be taken into account, i.e. there won't be props.settings
in Home
.
A proper solution is to not mix OOP with functional programming in this case. The behaviour from CustomRouteViewComponent
could be achieved via HOC or the composition of mapStateToProps
functions.
Upvotes: 1