Last active
June 18, 2018 10:03
-
-
Save akabab/3b43c8069b762c7ffb1a530414ae6d01 to your computer and use it in GitHub Desktop.
Redux exemple
This file contains hidden or 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 } from 'react' | |
import store from './store.js' | |
class App extends Component { | |
componentDidMount() { | |
// subscribe to changes -> forceUpdate will ask React to re-render the view | |
this.unsubscribe = store.subscribe(() => this.forceUpdate()) | |
} | |
componentWillUnmount() { | |
// when component is removed from the view -> remove the subscription | |
this.unsubscribe() | |
} | |
render() { | |
const state = store.getState() | |
return ( | |
<div className="App"> | |
<span>Counter: {state.counter}</span> | |
<button onClick={() => store.dispatch({ type: 'INCREMENT_COUNTER' })}>Increment</button> | |
<button onClick={() => store.dispatch({ type: 'INCREMENT_COUNTER_BY_N', n: 10 })}>Increment by 10</button> | |
</div> | |
) | |
} | |
} |
This file contains hidden or 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
const initialState = { | |
counter: 0 | |
} | |
const reducer = (state = initialState, action) => { | |
switch (action.type) { | |
case 'INCREMENT_COUNTER': { | |
return { | |
...state, | |
counter: counter + 1 | |
} | |
} | |
case 'INCREMENT_COUNTER_BY_N': { | |
return { | |
...state, | |
counter: counter + action.n // n is passed through the action object | |
} | |
} | |
default: return state | |
} | |
} | |
export default reducer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment