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';
  5. var middlewares = compose(applyMiddleware(thunk), autoRehydrate());
  6. export default function configureStore() {
  7. const store = createStore(reducers, undefined, middlewares);
  8. return store;
  9. }

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';
  3. function shouldFetchAllTodos(state) {
  4. const data = state.todos;
  5. if (data && data.isFetchingAllTodos) {
  6. return false
  7. }
  8. return true;
  9. }
  10. export function fetchAllTodos() {
  11. return async (dispatch, getState) =>{
  12. //verify
  13. if(!shouldFetchAllTodos(getState())){
  14. return Promise.resolve();
  15. }
  16. //dispatch fetch start action
  17. dispatch({type: types.START_FETCH_ALL_TODOS});
  18. //fetching
  19. const response = await fetch(APIs.allTodos);
  20. //response
  21. const data = await response.json();
  22. //dispatch fetch end action
  23. return dispatch({
  24. type: types.FETCH_ALL_TODOS,
  25. data
  26. });
  27. }
  28. }

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});
  5. case types.FETCH_ALL_TODOS:
  6. return Object.assign({}, state, {
  7. isFetchingAllTodos: false,
  8. data: action.data.data.reduce(function (pre, cur) {
  9. //remove duplicates
  10. !pre.find( key=> key.id===cur.id) && pre.push(cur);
  11. return pre;
  12. }, [...state.data])
  13. });
  14. ...
  15. ...
  16. default:
  17. return state
  18. }
  19. }

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. ...

 5.1 Fetch  - 图1

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