4.2 react-redux

1.Actions

1. import * as  navigationActions from './navigation';
2. import * as  todosActions from './todos';

4. export default {...navigationActions, ...todosActions};

2.combineReducers()

1. import { combineReducers } from 'redux';
2. import navigation from './navigation';
3. import todos from './todos';

5. const rootReducer = combineReducers({
6. navigation, todos
7. });

9. export default rootReducer;

3.Application state by configureStore()

1. import { createStore } from 'redux';
2. import reducers from '../reducers';

4. export default function configureStore() {
5. const store = createStore(reducers);
6. return store;
7. }

4.mapStateToProps & mapDispatchToProps & bindActionCreators

1. import { bindActionCreators } from 'redux';
2. import { connect } from 'react-redux';

4. class App extends Component {
5. renderTodoList = ()=>{
6. //reder todo list
7. return this.props.todos.map( (todo)=> {
8. return <Text key={todo.id}>Todo: {todo.title}</Text>
9. });
10. }
11. handleAddTodo = ()=>{
12. this.props.actions.addTodoAction('Create a new todo', 8);
13. }
14. render() {
15. return (
16. <View>
17. <TouchableHighlight onPress={this.handleAddTodo}>
18. <Text>Add Todo</Text>
19. </TouchableHighlight>
20. <ScrollView>{this.renderTodoList()}</ScrollView>
21. </View>
22. );
23. }
24. }

26. function mapStateToProps(state) {
27. return {
28. todos: state.todos
29. };
30. }

32. function mapDispatchToProps(dispatch) {
33. return {
34. actions: bindActionCreators(Actions, dispatch)
35. }
36. }

38. export default connect(
39. mapStateToProps,
40. mapDispatchToProps
41. )(App);

5.Passing the Store with <Provider/>

1. import React, { Component } from 'react';
2. import { Provider } from 'react-redux';

4. import App from './containers/App';
5. import configureStore from './store/configureStore';

7. class Root extends Component {
8. render() {
9. return (
10. <Provider store={configureStore()}>
11. <App />
12. </Provider>
13. );
14. }
15. }

17. export default Root;

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