4.2 react-redux

1.Actions

  1. import * as navigationActions from './navigation';
  2. import * as todosActions from './todos';
  3. export default {...navigationActions, ...todosActions};

2.combineReducers()

  1. import { combineReducers } from 'redux';
  2. import navigation from './navigation';
  3. import todos from './todos';
  4. const rootReducer = combineReducers({
  5. navigation, todos
  6. });
  7. export default rootReducer;

3.Application state by configureStore()

  1. import { createStore } from 'redux';
  2. import reducers from '../reducers';
  3. export default function configureStore() {
  4. const store = createStore(reducers);
  5. return store;
  6. }

4.mapStateToProps & mapDispatchToProps & bindActionCreators

  1. import { bindActionCreators } from 'redux';
  2. import { connect } from 'react-redux';
  3. class App extends Component {
  4. renderTodoList = ()=>{
  5. //reder todo list
  6. return this.props.todos.map( (todo)=> {
  7. return <Text key={todo.id}>Todo: {todo.title}</Text>
  8. });
  9. }
  10. handleAddTodo = ()=>{
  11. this.props.actions.addTodoAction('Create a new todo', 8);
  12. }
  13. render() {
  14. return (
  15. <View>
  16. <TouchableHighlight onPress={this.handleAddTodo}>
  17. <Text>Add Todo</Text>
  18. </TouchableHighlight>
  19. <ScrollView>{this.renderTodoList()}</ScrollView>
  20. </View>
  21. );
  22. }
  23. }
  24. function mapStateToProps(state) {
  25. return {
  26. todos: state.todos
  27. };
  28. }
  29. function mapDispatchToProps(dispatch) {
  30. return {
  31. actions: bindActionCreators(Actions, dispatch)
  32. }
  33. }
  34. export default connect(
  35. mapStateToProps,
  36. mapDispatchToProps
  37. )(App);

5.Passing the Store with <Provider/>

  1. import React, { Component } from 'react';
  2. import { Provider } from 'react-redux';
  3. import App from './containers/App';
  4. import configureStore from './store/configureStore';
  5. class Root extends Component {
  6. render() {
  7. return (
  8. <Provider store={configureStore()}>
  9. <App />
  10. </Provider>
  11. );
  12. }
  13. }
  14. export default Root;

原文: https://unbug.gitbooks.io/react-native-training/content/42_react-redux.html