Last active
July 11, 2018 08:15
-
-
Save drcmda/db7d8fd924bf39620533a0419fba08fc to your computer and use it in GitHub Desktop.
Context with Reduxes connect semantics
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
import React, { Component, PureComponent } from 'react' | |
import { render } from 'react-dom' | |
import Store, { connect } from './store' | |
@connect(({ users, setUserName }, { id }) => ({ ...users[id], setUserName })) | |
class User extends PureComponent { | |
change = ({ target: { value } }) => | |
this.props.setUserName(this.props.id, value) | |
render() { | |
const { name, id } = this.props | |
console.log(`component ${id} renders`) | |
return ( | |
<div> | |
<input value={name} onChange={this.change} /> | |
{name} | |
</div> | |
) | |
} | |
} | |
@connect(store => ({ ids: store.ids })) | |
class Users extends PureComponent { | |
render() { | |
return this.props.ids.map(id => <User key={id} id={id} />) | |
} | |
} | |
const state = { | |
users: { | |
1: { id: 1, name: 'Max' }, | |
2: { id: 2, name: 'Catherine' } | |
}, | |
ids: [1, 2] | |
} | |
const App = () => ( | |
<Store default={state}> | |
<Users /> | |
</Store> | |
) | |
render(<App />, document.getElementById('root')) |
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
import React, { Component, PureComponent } from 'react' | |
const { Provider, Consumer } = React.createContext() | |
class RenderPure extends PureComponent { | |
render() { | |
return this.props.children | |
} | |
} | |
export const connect = mapContextToProps => Component => props => ( | |
<Consumer | |
children={store => ( | |
<Component | |
{...props} | |
{...mapContextToProps(store, props)} | |
update={store.update} | |
/> | |
)} | |
/> | |
) | |
export default class Store extends Component { | |
constructor(props) { | |
super(props) | |
this.state = { | |
...props.default, | |
update: this.setState.bind(this), | |
setUserName: (id, name) => | |
this.setState(state => ({ | |
users: { ...state.users, [id]: { ...state.users[id], name } } | |
})) | |
} | |
} | |
render() { | |
return ( | |
<Provider | |
value={this.state} | |
children={<RenderPure children={this.props.children} />} | |
/> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment