Last active
September 1, 2015 00:39
-
-
Save ide/1da8a70a14535835da30 to your computer and use it in GitHub Desktop.
Redux batching example with React Native
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
/** | |
* Batched updates test with Redux. You will need React 0.6.0 and a .babelrc: | |
{ | |
"whitelist": [ | |
"es6.parameters.default", | |
"es7.decorators" | |
] | |
} | |
*/ | |
'use strict'; | |
var React = require('react-native'); | |
var { | |
AppRegistry, | |
StyleSheet, | |
Text, | |
TouchableOpacity, | |
View, | |
} = React; | |
var { createRedux } = require('redux'); | |
var { connect, provide } = require('redux/react-native'); | |
// Action types | |
var INCREMENT_ACTION = 'increment'; | |
// Action creators | |
function increment() { | |
return { type: INCREMENT_ACTION }; | |
} | |
// Stores | |
function CountStore(state = 0, action) { | |
if (action.type === INCREMENT_ACTION) { | |
return state + 1; | |
} | |
return state; | |
} | |
var redux = createRedux({ count: CountStore }); | |
@provide(redux) | |
class ReduxBatching extends React.Component { | |
render() { | |
return ( | |
<View style={styles.container}> | |
<Text style={styles.welcome}> | |
Redux batching demo (tap below) | |
</Text> | |
<Parent /> | |
</View> | |
); | |
} | |
} | |
@connect(state => state) | |
class Parent extends React.Component { | |
constructor() { | |
super(); | |
this._increment = this._increment.bind(this); | |
} | |
render() { | |
let { count } = this.props; | |
console.log(`[Parent.render] count=${count}`); | |
return ( | |
<TouchableOpacity onPress={this._increment}> | |
<View style={styles.parent}> | |
<Text>Parent: {count}</Text> | |
<Child parentCount={count} /> | |
</View> | |
</TouchableOpacity> | |
); | |
} | |
_increment() { | |
this.props.dispatch(increment()); | |
} | |
} | |
@connect(state => state) | |
class Child extends React.Component { | |
render() { | |
let { count, parentCount } = this.props; | |
// We want a consistent view of the world: parentCount should match count | |
console.log(`[Child.render] count=${count} parentCount=${parentCount}`); | |
return <Text>Child: {count}</Text>; | |
} | |
} | |
var styles = StyleSheet.create({ | |
container: { | |
flex: 1, | |
justifyContent: 'center', | |
alignItems: 'center', | |
backgroundColor: '#F5FCFF', | |
}, | |
welcome: { | |
fontSize: 20, | |
textAlign: 'center', | |
margin: 10, | |
}, | |
parent: { | |
borderWidth: 0.5, | |
} | |
}); | |
AppRegistry.registerComponent('ReduxBatching', () => ReduxBatching); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment