State consumer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ConnectState extends React.Component { | |
state = this.props.mapState(this.props.state); | |
static getDerivedStateFromProps (nextProps, nextState) {} | |
shouldComponentUpdate (nextProps) { | |
if (!Object.keys(this.state).length) { | |
this.setState(this.props.mapDispatch(this.props.state)); | |
return true; | |
} | |
console.log({ | |
s: this.state, | |
nextState: nextProps.mapState(nextProps.state), | |
state: this.props.mapState(this.state) | |
}); | |
return false; | |
} | |
render () { | |
return this.props.children({ state: this.props.state, dispatch: this.props.dispatch }); | |
} | |
} | |
export function StateConsumer ({ mapState, mapDispatch, children }) { | |
return ( | |
<StateContext.Consumer> | |
{({ state, dispatch }) => ( | |
<ConnectState state={state} dispatch={dispatch} mapState={mapState} mapDispatch={mapDispatch}> | |
{children} | |
</ConnectState> | |
)} | |
</StateContext.Consumer> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment