【问题标题】:Where I handle API calls in react-native and redux我在 react-native 和 redux 中处理 API 调用的地方
【发布时间】:2016-11-08 11:04:40
【问题描述】:

我正在使用 react-native + redux + immutable 构建一个 Android 应用程序

我的应用是这样构建的

/src
 -/components
 -/actions (where I have action types and actions)
 -/reducers
 -/api (I'm not sure if I'm doing this right)

好的,所以我有一个操作需要使用 fetch 进行 API 调用,如下所示:

import * as types from './casesTypes'

export function getCases() {
    return {
      type: types.GET_CASES
    }
}

这是case reducer:

const initialState = fromJS({
  isLoading: false,
  cases: null
})
export default function cases(state = initialState, action = {}) {

    switch(action.type) {

        case types.REQUEST_CASES:
          return state.set('isLoading', true)

        case types.RECIVE
          return state.set('cases', //set here the array that I recive from api call)

        default:
          return state
    }
}

所以,问题是我真的不明白,我应该在哪里进行 API 调用,以便在 reducer 中我可以将我的初始状态与我从 API 调用中收到的内容合并?

【问题讨论】:

    标签: reactjs react-native redux react-redux


    【解决方案1】:

    您的应用程序结构合理。

    我还推荐使用 redux-thunk 来处理调度。以下是它在您的情况下的工作方式:

    假设您的状态树中有“案例”。 我会按照您的建议将 API 调用放入您的操作中以获取新案例:

    import * as types from './casesTypes'
    
    export function getCases() {
        return fetch(...)
                 ...
                 .then((json) => {
                   dispatch({         
                     type: types.RECEIVED_CASES,
                     isLoading: false,
                     cases: json,
                   }
    }
    

    现在在你的 reducer 中,只需获取新调度的操作即可将新案例与状态树合并:

    const initialState = fromJS({
      isLoading: false,
      cases: null
    })
    
    export default function cases(state = initialState, action = {}) {
    
        switch(action.type) {
    
            case types.REQUEST_CASES:
              return state.set('isLoading', true)
    
            case types.RECEIVED_CASES:
              return Object.assign({}, state, {
                cases: state.cases.merge(action.cases),
              });
    
            default:
              return state
        }
    }
    

    我目前正在使用这种结构,并且效果很好。希望对您有所帮助!

    【讨论】:

      【解决方案2】:

      您应该尝试redux-thunkredux-saga,它们是为处理异步操作(如进行 API 调用)而创建的 redux 中间件。

      查看这个使用 redux-thunk 的项目:sound-redux-native

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-20
        • 1970-01-01
        • 1970-01-01
        • 2019-01-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多