2017-05-21 29 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减速器,只从您的服务器响应中提取加载数据。