2017-06-22 66 views
4

我有一個減速,看起來像這樣:減速返回減速的集合導致

const chart = combineReducers({ 
    data, 
    fetchProgress, 
    fetchError, 
    updateProgress, 
    updateError, 
}); 

現在我想不僅是一個圖表,但多個圖表。

const charts = (state = {}, action = {}) => { 
    if (action.type == FETCH_CHART || action.type == ...) { 
     let newChart = chart(state[action.id], action); 
     return Object.assign({}, state, {[action.id]: newChart}); 
    } 
    return state; 
} 

這樣做是否有什麼概念錯誤?

如果否,是否有更好的方法來實現相同的結果?

回答

1

這個概念沒有錯。實際上,當我需要將類似數據存儲在REDX存儲庫中時,我會說這是我首選的方法。要改進它,可以將它包裝在高階簡化器中以處理其中的id部分。喜歡的東西:

const handleIds = (reducer) => (state = {}, action) => { 
    if (action.id) { 
     let idState = state[action.id] 
     let newState = reducer(idState, action) 

     if (newState !== idState) { 
      return { ...state, [action.id]: newState } 
     } 
    } 

    return state 
} 

這會把任何行動的id和合並所產生的state到它stateid因爲它是關鍵,如果state發生了變化。

然後你減速變爲:

const singleChart = (state = {}, action = {}) => { 
    if (action.type == FETCH_CHART || action.type == ...) { 
     let newChart = chart(state, action); 
     return newChart; 
    } 
    return state; 
} 

const charts = handleIds(singleChart) 

然後將其合併到您的商店:

const chart = combineReducers({ 
    data, 
    fetchProgress, 
    fetchError, 
    updateProgress, 
    updateError, 
    charts 
}); 
1

個人而言,我會崩潰,以進一步細分減速的邏輯有更好的分離的擔憂。如果您將添加多個圖表,並且萬一您需要爲您的操作添加更多的邏輯/設置/數據,您將最終修改過多的單個縮減器。

我遵循一個小例子,你可以有3個圖表。

// bubbleChartReducer.js 
export function bubble (state = {}, action) { 
    switch (action.type) { 
    case 'FETCH_BUBBLE_CHART': 
     return { 
     [action.id]: new chart(action.id, action) 
     } 
    default: 
     return state 
    } 
} 

// pieChartReducer.js 
export function pie (state = {}, action) { 
    switch (action.type) { 
    case 'FETCH_PIE_CHART': 
     return { 
     [action.id]: new chart(action.id, action) 
     } 
    default: 
     return state 
    } 
} 

// linearChartReducer.js 
export function pie (state = {}, action) { 
    switch (action.type) { 
    case 'FETCH_LINEAR_CHART': 
     return { 
     [action.id]: new chart(action.id, action) 
     } 
    default: 
     return state 
    } 
} 



// chartsReducer.js 
import { bubble } from 'bubbleChartReducer' 
import { pie } from 'pieChartReducer' 
import { linear } from 'linearChartReducer' 
import { combineReducers } from 'redux' 

export combineReducers({ 
    bubble, 
    pie, 
    linear 
})