简体   繁体   中英

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

I'm making a to-do app with react-typescript-redux and want to fetch todos from my server. When I hardcode todos, using this.props.getTodos['todo1','todo2'] in my container, everything works, but when I try to do it asynchronously,using this.props.requestTodos() - it doesn't. When I use this.props.requestTodos() response from the server reaches the getTodos actionCreator but for some reason the action object doesn't reach the reducer, so the state doesn't get updated. How do I fix this? 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));
    };
};

Store:

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

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

Reducer:

const rootReducer = combineReducers({
    todoItems,
});

TodoItems(reducer):

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

Container component:

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

}

Looks like you're calling getTodos() , but not actually dispatching it. Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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