2017-03-07 13 views
5

में मेरी प्रतिक्रिया/redux/आवेदन मैं जैसे कार्यों का उपयोग thunk। सबकुछ काम करता है लेकिन मेरे पास प्रत्येक डेटा इकाई (और स्थिरांक भी) के लिए बहुत सी कोड है। मेरा मतलब कुत्तों, बाघों, पक्षियों आदि के लिए समान कार्य है ...कैसे refactor करने के लिए redux + thunk कार्रवाई/स्थिरांक

मुझे लगता है कि प्रत्येक इकाई के लिए समान अनुरोध/प्राप्त/असफल कार्रवाई/स्थिरता है।

रेडक्स-थंक के संदर्भ में कोड को कम करने का सही तरीका क्या है?

प्रकार:

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

thunk:

+1

https://www.npmjs.com/package/redux-api-middleware पर विचार करें –

उत्तर

4

तुम एक प्रकार है और एक 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 })); 
     }); 
}); 

नहीं, तुम 2 के साथ एक विधि लाने बना सकते हैं कोड की रेखाएं:

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 

नोट: आप reducers में निरंतर प्रकार (fetchDogsTypes) का भी उपयोग करेंगे।

संबंधित मुद्दे