2017-05-21 61 views
0

我正在編寫一個使用後端的應用程序,並且當我打開應用程序時我需要進行編寫。向服務器發出請求,請求正確的狀態。應該重寫整個應用程序狀態。如何覆蓋Redux中的初始狀態

但現在,我只能將其分配給設施「加載/數據」,並且只需要完全覆蓋Root Redux狀態。從服務器

響應:http://i.imgur.com/yams0M4.jpg

Redux的狀態:http://i.imgur.com/URCCZkN.jpg

動作/ loading.js

export function fetchTodos(path) { 
    return function (dispatch) { 
    dispatch({ 
     type: FETCH_TODOS_REQUEST, 
    }); 
    return axios 
     .get(`http://localhost:3000${path}`) 
     .then((response) => { 
     const { data } = response; 
     console.log('data', data); 
     dispatch({ 
      type: FETCH_TODOS_SUCCESS, 
      data, 
     }); 
     }) 
     .catch((error) => { 
     const { data } = error.response; 
     console.log('data', data); 
     dispatch({ 
      type: FETCH_TODOS_FAILURE, 
      error: data, 
     }); 
     }); 
    }; 

減速器/ index.js

const rootReducer = combineReducers({ 
    loading, 
    Header, 
    Main, 
    routing: routerReducer, 
}); 

export default rootReducer; 

減速器/ loading.js

export function loading(state = initialState.loading, action) { 
    switch (action.type) { 
    case FETCH_TODOS_REQUEST: 
     return Object.assign({}, state, { 
     isFetching: true, 
     }); 
    case FETCH_TODOS_SUCCESS: 
     return Object.assign({}, state, { 
     isFetching: false, 
     data: action.data.data, 
     }); 
    case FETCH_TODOS_FAILURE: 
     return Object.assign({}, state, { 
     isFetching: false, 
     error: action.error, 
     }); 
    default: 
     return state; 
    } 
} 

店/ index.js

function configureStoreProd(initialState) { 
    return createStore(rootReducer, initialState); 
} 

function configureStoreDev(initialState) { 
    const middlewares = [ 
    thunk, 
    ]; 
    const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; 
    const store = createStore(rootReducer, initialState, composeEnhancers(
    applyMiddleware(...middlewares), 
    ), 
); 

回答

0

您需要連接到FETCH_TODOS_SUCCESS行動在HeaderMain減速機。

當組合縮減器時,每個縮減器的state數據僅包含該縮減器的段。

例如,您的loading減速機將有權訪問您商店的state.loading部分。要更新您的商店的Main段,你可以這樣做:

// reducers/Main.js 

export default (state = initialState.Main, action) => { 
    switch (action.type) { 
     case FETCH_TODOS_SUCCESS: 
      const newMainData = action.data.data.main; 

      return Object.assign({}, state, newMainData); 
     default: 
      return state; 
    } 
} 

作爲一個側面說明,你應該爲實例型變量只有用戶大寫變量(例如類狀物體)。

此外,不要忘記更新您的loading減速器,只從您的服務器響應中提取加載數據。