2016-07-06 76 views
7

我建立使用react-native + redux + immutable当我处理API调用反应本机和终极版

我构建我的应用程序是这样

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

好了一个Android应用程序,所以我有一个行动,我需要做的API调用与获取这样的:

import * as types from './casesTypes' 

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

这是案件减速机:

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调用,以便在缩减器中我可以合并我的初始状态与我从API调用中收回的状态?

回答

7

您的应用程序结构是健全的。

我还推荐使用redux-thunk来处理分派。以下是它如何在你的情况下工作:

假设你有'案件'作为你的状态树的一部分。 我会把API调用你的行动,你提出来获取新的情况:

import * as types from './casesTypes' 

export function getCases() { 
    return fetch(...) 
      ... 
      .then((json) => { 
       dispatch({   
       type: types.RECEIVED_CASES, 
       isLoading: false, 
       cases: json, 
       } 
} 

现在在你的减速刚刚拿到新调遣行动合并新例的州树:

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中间件。

退房这个项目所用终极版-的thunk:sound-redux-native

相关问题