Created
February 14, 2017 01:08
-
-
Save WearyMonkey/6f405b3bfa88b7659b14556e9b24cb31 to your computer and use it in GitHub Desktop.
Connected vs Top Down
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 * as React from 'react'; | |
import * as ReactDOM from 'react-dom'; | |
import { createStore, Store } from 'redux'; | |
import { connect, Provider } from 'react-redux'; | |
import ReactElement = React.ReactElement; | |
import { List } from 'immutable'; | |
const values = List<number>().withMutations(list => { | |
for (let i = 0; i < 1000; ++i) list.push(i); | |
}); | |
function reducer(state: List<number> = values, action : any) : List<number> { | |
switch (action.type) { | |
case 'INCR': return state.set(action.index, state.get(action.index) + 1); | |
default: return state; | |
} | |
} | |
function ChildComponent({value, onClick}: {value: number, onClick: () => void}): ReactElement<{value: number}> { | |
return <div><button onClick={onClick}>increment</button>{value}</div>; | |
} | |
function createConnectChildComponent(index: number): React.ComponentClass<{}> { | |
return connect((state: List<number>) => ({ | |
value: state.get(index) | |
}), { | |
onClick: () => ({ type: 'INCR', index }) | |
})(ChildComponent); | |
} | |
class Connected extends React.Component<{store: Store<List<number>>}, {}> { | |
render() { | |
return (<Provider store={this.props.store}> | |
<div> | |
{values.map((_, i) => { | |
const Child = createConnectChildComponent(i); | |
return <Child key={i} /> | |
})} | |
</div> | |
</Provider>); | |
} | |
} | |
class TopDown extends React.Component<{store: Store<List<number>>}, {values: List<number>}> { | |
componentWillMount() { | |
const { store } = this.props; | |
this.setState({values: store.getState()}); | |
store.subscribe(() => { | |
this.setState({values: store.getState()}); | |
}); | |
} | |
render() { | |
return (<div> | |
{this.state.values.map((value, index) => | |
<ChildComponent key={index} value={value} onClick={() => this.props.store.dispatch({type: 'INCR', index})} />)} | |
</div>); | |
} | |
} | |
ReactDOM.render(<Connected store={createStore(reducer)} />, document.getElementById('root1')); | |
ReactDOM.render(<TopDown store={createStore(reducer)} />, document.getElementById('root2')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment