2016-09-17 65 views
0

我有一個react-redux應用程序,它包含一個提供數據的表組件和一個通過下拉列表過濾數據的過濾組件。我需要更改我的應用程序,以便每次使用下拉菜單進行選擇時都可以從後端接收數據。我有以下內容:組件,縮減器,動作創建器,mapStateToProps和mapDispatchToProps。我應該在哪個後端調用?從React Redux調用後端

+0

你可以從你的'action creators'或'component'本身調用它,或者你可以想到的任何其他方法/地方。我不建議從**'reducers' **,'mapStateToProps '或'mapDispatchToProps' –

+0

看看redux-thunk庫。它的作用是允許你編寫返回函數的動作創建者,當調用這些動作創建者時,它也會調用函數並傳遞redux派發方法。 然後,您可以使用mapDispatchToProps中間件,通過道具傳遞這些動作創建者,並且可以從組件中調用它們。然後,您可以針對檢索事件進行操作,這可以在請求回調到後端的過程中分派。然後Reducer將處理來自該動作的數據存儲,並且當道具更新時,您已更新組件中的數據。 –

回答

2

您可以使用redux midleware在您的操作中暴露api客戶端。

我的終極版中間件:

export default function clientMiddleware(client) { 
    return ({ dispatch, getState }) => next => action => { 
    if (typeof action === 'function') { 
     return action(dispatch, getState); 
    } 

    const { promise, types, ...rest } = action; // eslint-disable-line no-redeclare 
    if (!promise) { 
     return next(action); 
    } 

    const [REQUEST, SUCCESS, FAILURE] = types; 
    next({ ...rest, type: REQUEST }); 

    const { auth } = getState(); 

    client.setJwtToken(auth.token || null); 

    const actionPromise = promise(client, dispatch); 
    actionPromise.then(
     result => next({ ...rest, result, type: SUCCESS }), 
     error => next({ ...rest, error, type: FAILURE }) 
    ).catch((error) => { 
     console.error('MIDDLEWARE ERROR:', error); 
     next({ ...rest, error, type: FAILURE }); 
    }); 

    return actionPromise; 
    }; 
} 

其在動作使用:

const SAVE = 'redux-example/widgets/SAVE'; 
const SAVE_SUCCESS = 'redux-example/widgets/SAVE_SUCCESS'; 
const SAVE_FAIL = 'redux-example/widgets/SAVE_FAIL'; 

export function save(widget) { 
    return { 
    types: [SAVE, SAVE_SUCCESS, SAVE_FAIL], 
    id: widget.id, // additionnal data for reducer 
    promise: client => client.post('/widget/update', { 
     data: widget 
    }) 
    }; 
} 

// in reducer: 
export default function reducer(state = initialState, action = {}) { 
    switch (action.type) { 
    case SAVE: 
     return state; 
    case SAVE_SUCCESS: 
     // you can use action.result and action.id here 
     return state; 
    case SAVE_FAIL: 
     // and you can use action.error and action.id here 
     return state; 
    default: 
     return state; 
    } 
} 

最後,你必須通過這一行動與mapDispatchToProps您的組件。

希望能幫助你