2017-03-07 18 views
5

Trong tôi phản ứng/Redux/thunk ứng dụng tôi sử dụng những hành động như:Làm thế nào để cấu trúc lại Redux + thunk hành động/hằng

function catsRequested() { 
    return { 
     type: CATS_REQUESTED, 
     payload: {}, 
    }; 
} 

function catsReceived(landings) { 
    return { 
     type: CATS_RECEIVED, 
     payload: landings, 
    }; 
} 

function catsFailed(error) { 
    return { 
     type: CATS_FAILED, 
     payload: { error }, 
    }; 
} 

export const fetchCats =() => ((dispatch, getState) => { 
    dispatch(catsRequested()); 
    return catsAPI.loadCats() 
     .then((cats) => { 
      dispatch(catsReceived(cats)); 
     }, (e) => { 
      dispatch(catsFailed(e.message)); 
     }); 
}); 

Để đối phó với một số dữ liệu (giản thể). Tất cả mọi thứ hoạt động nhưng tôi có rất nhiều mã cho mỗi thực thể dữ liệu (và hằng số quá). Tôi có nghĩa là các chức năng giống nhau cho chó, hổ, chim, v.v ...

Tôi thấy có hành động/yêu cầu không được yêu cầu/nhận/thất bại tương tự cho mọi thực thể.

Cách nào đúng để giảm bớt mã theo dạng redux-thunk?

+1

xem xét https://www.npmjs.com/package/redux-api-middleware –

Trả lời

4

Bạn có thể giữ DRY mã của bạn bằng cách tạo ra một loại và một người sáng tạo thunk:

Loại:

const createTypes = (type) => ({ 
    request: `${type}_REQUESTED`, 
    received: `${type}_RECEIVED`, 
    failed: `${type}_FAILED`, 
}); 

thunk:

const thunkCreator = (apiCall, callTypes) => ((dispatch, getState) => { 
    dispatch({ type: callTypes.request }); 

    return apiCall 
     .then((payload) => { 
      dispatch({ type: callTypes.received, payload })); 
     }, (e) => { 
      dispatch({ type: callTypes.failed, payload: e.message })); 
     }); 
}); 

Không bạn có thể tạo ra một phương pháp lấy bằng 2 dòng mã:

export const fetchCatsTypes = createTypes('CATS'); // create and export the constants 
export const fetchCats = (catsAPI.loadCats, fetchCatsTypes); // create and export the thunk 

export const fetchDogsTypes = createTypes('DOGS'); // create and export the constants 
export const fetchDogs = (dogsAPI.loadDogs, fetchDogsTypes); // create and export the thunk 

Lưu ý: bạn cũng sẽ sử dụng các loại hằng số (fetchDogsTypes) trong bộ giảm tốc.

Các vấn đề liên quan