5.1 Fetch
1.apply redux-thunk middleware
1. import { applyMiddleware, createStore, compose } from 'redux';
2. import thunk from 'redux-thunk';
3. import createLogger from 'redux-logger';
4. import reducers from '../reducers';
6. var middlewares = compose(applyMiddleware(thunk), autoRehydrate());
8. export default function configureStore() {
9. const store = createStore(reducers, undefined, middlewares);
10. return store;
11. }
2.start & end action types
1. //todo action types
2. export const START_FETCH_ALL_TODOS = 'START_FETCH_ALL_TODOS';
3. export const FETCH_ALL_TODOS = 'FETCH_ALL_TODOS';
3.fetch flow
1. import * as types from '../constants/ActionTypes';
2. import * as APIs from '../constants/ServerAPIs';
5. function shouldFetchAllTodos(state) {
6. const data = state.todos;
7. if (data && data.isFetchingAllTodos) {
8. return false
9. }
10. return true;
11. }
13. export function fetchAllTodos() {
14. return async (dispatch, getState) =>{
15. //verify
16. if(!shouldFetchAllTodos(getState())){
17. return Promise.resolve();
18. }
20. //dispatch fetch start action
21. dispatch({type: types.START_FETCH_ALL_TODOS});
23. //fetching
24. const response = await fetch(APIs.allTodos);
25. //response
26. const data = await response.json();
28. //dispatch fetch end action
29. return dispatch({
30. type: types.FETCH_ALL_TODOS,
31. data
32. });
33. }
34. }
4.reducer
1. export default function todos(state = initialState, action) {
2. switch (action.type) {
3. case types.START_FETCH_ALL_TODOS:
4. return Object.assign({}, state, {isFetchingAllTodos: true});
6. case types.FETCH_ALL_TODOS:
7. return Object.assign({}, state, {
8. isFetchingAllTodos: false,
9. data: action.data.data.reduce(function (pre, cur) {
10. //remove duplicates
11. !pre.find( key=> key.id===cur.id) && pre.push(cur);
12. return pre;
13. }, [...state.data])
14. });
15. ...
16. ...
17. default:
18. return state
19. }
20. }
5.dispatch & render
1. ...
2. componentDidMount(){
3. //fetch data from server
4. this.props.actions.fetchAllTodos();
5. }
6. ...
7. ...
8. renderLoading = () => {
9. if (this.props.todos.isFetchingAllTodos) {
10. return (
11. <View style={styles.loading}>
12. <Text style={styles.loadingText}>Loading...</Text>
13. </View>
14. )
15. }
16. return null;
17. }
18. ...

原文: <https://unbug.gitbooks.io/react-native-training/content/51_fetch.html>
