【问题标题】:how to use redux-observerable when the network requset handle by axiosaxios处理网络请求时如何使用redux-observable
【发布时间】:2019-10-27 01:55:11
【问题描述】:

我想在我的项目中使用redux-observerable,因为可以取消if的动作。但是官方给出了使用rxjs的ajax的例子,我想使用axios作为网络库,如何实现.

示例代码:

const FETCH_USER = 'FETCH_USER';
const FETCH_USER_FULFILLED = 'FETCH_USER_FULFILLED';
const FETCH_USER_REJECTED = 'FETCH_USER_REJECTED';
const FETCH_USER_CANCELLED = 'FETCH_USER_CANCELLED';

const fetchUser = id => ({ type: FETCH_USER, payload: id });
const fetchUserFulfilled = payload => ({ type: FETCH_USER_FULFILLED, payload });
const cancelFetchUser = () => ({ type: FETCH_USER_CANCELLED });

const fakeAjax = url => of({
  id: url.substring(url.lastIndexOf('/') + 1),
  firstName: 'Bilbo',
  lastName: 'Baggins'
}).pipe(delay(1000));

const fetchUserEpic = action$ => action$.pipe(
  ofType(FETCH_USER),
  mergeMap(action => fakeAjax(`/api/users/${action.payload}`).pipe(
    map(response => fetchUserFulfilled(response)),
    takeUntil(action$.pipe(
      filter(action => action.type === FETCH_USER_CANCELLED)
    ))
  ))
);

const users = (state = {}, action) => {
  switch (action.type) {
    case FETCH_USER:
        return {};

    case FETCH_USER_FULFILLED:
      return {
        ...state,
        [action.payload.id]: action.payload
      };

    default:
      return state;
  }
};

const isFetchingUser = (state = false, action) => {
  switch (action.type) {
    case FETCH_USER:
      return true;

    case FETCH_USER_FULFILLED:
    case FETCH_USER_CANCELLED:
      return false;

    default:
      return state;
  }
};

我想用 axios 替换 fetchAjax

const fakeAjax = url,params =>{ return axios({
        method: 'post',
        url: url,
        data: params
    });
}

【问题讨论】:

    标签: react-native axios redux-observable


    【解决方案1】:

    我不明白使用 axios 的附加价值,因为 rxjs 的 ajax 会简化您的代码(它已经在使用 observables)。但是,如果你真的想要,那绝对是可能的。我假设在下面的示例中,您正在使用有效负载由 url 和请求数据组成的操作。

    const fetchUserEpic = action$ => action$.pipe(
      ofType(FETCH_USER),
      mergeMap(action => from(axios({method: 'get', action.payload.url, data: action.payload.data})).pipe(
        map(response => fetchUserFulfilled(response)),
        takeUntil(action$.ofType(FETCH_USER_CANCELLED)),
      ))
    );
    

    另外:请记住,取消将阻止 redux 存储更新,但不会取消处理 axios 请求。

    【讨论】:

      猜你喜欢
      • 2019-04-24
      • 2018-05-12
      • 2011-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-02
      • 2020-03-06
      • 2023-03-07
      相关资源
      最近更新 更多