redux中fetch的使用

看到一个项目中引入的是 import fetch from 'isomorphic-fetch';


然后在定义action—type时,写的:


export const FETCH_RUNS = 'FETCH_RUNS';

export const FETCH_RUNS_PENDING = 'FETCH_RUNS_PENDING';

export const FETCH_RUNS_FULFILLED = 'FETCH_RUNS_FULFILLED';

export const FETCH_RUNS_REJECTED = 'FETCH_RUNS_REJECTED';

加了三种状态pending,fulfilled,rejected


action中只写了type: FETCH_RUNS的:


import {fetchRuns} from '../../services/RunService';

const fetchRunsAction = (req) => ({

  type: FETCH_RUNS,

  payload: fetchRuns(req)

});

export {

  fetchRunsAction as fetchRuns

}

而在reducer中对三种状态的action都做了处理:


import {

  FETCH_RUNS_FULFILLED,

  FETCH_RUNS_PENDING,

  FETCH_RUNS_REJECTED

} from '../actions/runActions';



// INITIALIZE STATE


const initialState = {

  runs: null,

  fetched: false,

  fetching: false,

  failed: false

};



// REDUCER


export const FetchRunsReducer = (state = initialState, action) => {

  switch (action.type) {

    case FETCH_RUNS_PENDING:

      return {

        ...state,

        fetching: true,

        fetched: false,

        failed: false

      };

    case FETCH_RUNS_FULFILLED:

      return {

        ...state,

        runs: action.payload,

        fetching: false,

        fetched: true,

        failed: false

      };

    case FETCH_RUNS_REJECTED:

      return {

        ...state,

        runs: null,

        fetching: false,

        fetched: false,

        failed: true

      };

    default:

      return state;

  }

};

在组件中:


...

const mapStateToProps = state => {

  const {fetched, fetching, runs} = state.runs;


  return {

    fetched,

    fetching,

    runs

  };

};


const mapDispatchToProps = dispatch => {

  return bindActionCreators({fetchRuns}, dispatch);

};

现在我的疑惑点在——什么时候触发了FETCH_RUNS_PENDING,FETCH_RUNS_FULFILLED,FETCH_RUNS_REJECTED这三个状态;在promise是有三个状态,自动触发,但是程序如何跳到代码中写的这三个action名字FETCH_RUNS_PENDING,FETCH_RUNS_FULFILLED,FETCH_RUNS_REJECTED;我想是不是某个封装的地方给action名字自动后面添加了PENDING、FULFILLED,REJECTED然后在触发此action的时候后自动触发这几个状态的action。那么请问在哪个里面进行了封装呢?代码中没有找到啊,是不是react,redux某个里面封装的?求助


繁星coding
浏览 816回答 1
1回答

倚天杖

你少最重要的一部分,就是处理 action 那部分现在我的疑惑点在——什么时候触发了FETCH_RUNS_PENDING,FETCH_RUNS_FULFILLED,FETCH_RUNS_REJECTED这三个状态;在promise是有三个状态,自动触发,手动触发或者自己写个工具触发总之不会自动触发,但是程序如何跳到代码中写的这三个action名字你在找着代码 看最终 action 被那个组件使用了FETCH_RUNS_PENDING,FETCH_RUNS_FULFILLED,FETCH_RUNS_REJECTED;我想是不是某个封装的地方给action名字自动后面添加了PENDING、FULFILLED,REJECTED然后在触发此action的时候后自动触发这几个状态的action。那么请问在哪个里面进行了封装呢?代码中没有找到啊,是不是react,redux某个里面封装的?求助可以这样做 但是很明显这个不是这样做的
打开App,查看更多内容
随时随地看视频慕课网APP