繁体   English   中英

使用redux-thunk时,动作对象未到达减速器

[英]Action object doesn't reach the reducer when using redux-thunk

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

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(),
    ));

减速器:

const rootReducer = combineReducers({
    todoItems,
});

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;
  }
}

容器组件:

class TodoList extends React.Component<IProps, {}> {

    public componentDidMount(): any {
        // tslint:disable-next-line:no-expression-statement
        this.props.requestTodos();
    }

    public render(): JSX.Element {
        const todoItems = this.props.todoItems.map((text, i) => (
            <TodoItem key={i} text={text} />
        ));

        return(
            <div>
                <ul className='todo-list'>
                    {todoItems}
                </ul>
            </div>
        );
    }

}

看起来您正在调用 getTodos() ,但实际上并未调度它。 尝试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM