4.1 Redux
1.Actions & Action Creators
1. //action type
2. const ADD_TODO = 'ADD_TODO';
4. //action creator, semantic methods that create actions
5. //collected together in a module to become an API
6. function addTodoAction(title, hour) {
7. //action, an object with a type property and new data, like events
8. return {type: ADD_TODO, title, hour}
9. }
2.Reducers
1. //a function that accepts an accumulation and a value and returns a new accumulation.
2. function todoReducers(state = [], action) {
3. switch (action.type) {
4. case ADD_TODO:
5. //always return a new state, never mutate old state
6. return [
7. {
8. id: Utils.GUID(),
9. title: action.title,
10. endTime: getEndTime(action.hour),
11. completed: false
12. },
13. ...state
14. ]
15. default:
16. //return default state
17. return state
18. }
19. }
3.Store
1. import { createStore } from 'redux';
2. //1. define store
3. let store = createStore(todoReducers);
5. class App extends Component {
6. constructor(props){
7. super(props);
8. this.state = {todos: []};
9. }
10. componentDidMount(){
11. //2. subscribe store
12. this.unsubscribeStore = store.subscribe(() =>{
13. //3. getState
14. this.setState({todos: store.getState()});
15. });
16. }
17. componentWillUnmount(){
18. //5. unsubscribe store
19. this.unsubscribeStore();
20. }
21. renderTodoList = ()=>{
22. //reder todo list
23. return this.state.todos.map( (todo)=> {
24. return <Text key={todo.id}>Todo: {todo.title}</Text>
25. });
26. }
27. handleAddTodo = ()=>{
28. //4. dispatching actions
29. store.dispatch( addTodoAction('Create a new todo', 8) );
30. }
31. render() {
32. return (
33. <View>
34. <TouchableHighlight onPress={this.handleAddTodo}>
35. <Text>Add Todo</Text>
36. </TouchableHighlight>
37. <ScrollView>{this.renderTodoList()}</ScrollView>
38. </View>
39. );
40. }
41. }
4.Data flow



原文: <https://unbug.gitbooks.io/react-native-training/content/41_redux+react.html>
