使用redux-thunk时,Action对象不会到达reducer

时间:2017-07-13 22:08:18

标签: reactjs redux react-redux redux-thunk

我正在使用react-typescript-redux创建一个待办事项应用程序,并希望从我的服务器获取待办事项。当我硬编码待办事项时,在我的容器中使用ByVal,一切正常,但当我尝试异步地使用this.props.getTodos['todo1','todo2']时 - 它没有。当我使用来自服务器的this.props.requestTodos()响应到达this.props.requestTodos() actionCreator时,但由于某种原因,操作对象没有到达reducer,因此状态不会更新。我该如何解决? actionCreators:

getTodos

商店:

export const getTodos = (todoItems: ReadonlyArray<string>) => {
    return {
        type: Constants.GET_TODOS as typeof Constants.GET_TODOS,
        payload: {todoItems},
    };
};

export const requestTodos = () => {
    return (dispatch: any) => {
        // tslint:disable-next-line:no-expression-statement
        axios('/todos')
        .then((todos: any) => getTodos(JSON.parse(todos.data).todos))
        .catch((err: any) => console.log(err));
    };
};

减速器:

const defaultState: IDefaultState = {
    todoItems: [],
};

const store = createStore(
    rootReducer,
    defaultState,
    applyMiddleware(
        thunk,
        createLogger(),
    ));

TodoItems(减速器):

const rootReducer = combineReducers({
    todoItems,
});

容器组件:

function todoItems(state = ([] as ReadonlyArray<string>), action: any): any {
  switch (action.type) {
    case Constants.GET_TODOS:
      return [
        ...state,
        action.payload.todoItems,
      ];
    default:
      return state;
  }
}

1 个答案:

答案 0 :(得分:3)

您似乎正在调用 getTodos(),但实际上并未调度。试试这个:

.then((todos: any) => dispatch(getTodos(JSON.parse(todos.data).todos)))