4.1 Redux

1.Actions & Action Creators

  1. //action type
  2. const ADD_TODO = 'ADD_TODO';
  3. //action creator, semantic methods that create actions
  4. //collected together in a module to become an API
  5. function addTodoAction(title, hour) {
  6. //action, an object with a type property and new data, like events
  7. return {type: ADD_TODO, title, hour}
  8. }

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);
  4. class App extends Component {
  5. constructor(props){
  6. super(props);
  7. this.state = {todos: []};
  8. }
  9. componentDidMount(){
  10. //2. subscribe store
  11. this.unsubscribeStore = store.subscribe(() =>{
  12. //3. getState
  13. this.setState({todos: store.getState()});
  14. });
  15. }
  16. componentWillUnmount(){
  17. //5. unsubscribe store
  18. this.unsubscribeStore();
  19. }
  20. renderTodoList = ()=>{
  21. //reder todo list
  22. return this.state.todos.map( (todo)=> {
  23. return <Text key={todo.id}>Todo: {todo.title}</Text>
  24. });
  25. }
  26. handleAddTodo = ()=>{
  27. //4. dispatching actions
  28. store.dispatch( addTodoAction('Create a new todo', 8) );
  29. }
  30. render() {
  31. return (
  32. <View>
  33. <TouchableHighlight onPress={this.handleAddTodo}>
  34. <Text>Add Todo</Text>
  35. </TouchableHighlight>
  36. <ScrollView>{this.renderTodoList()}</ScrollView>
  37. </View>
  38. );
  39. }
  40. }

4.Data flow

 4.1 Redux  - 图1

 4.1 Redux  - 图2

 4.1 Redux  - 图3

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