2017-07-13 67 views
0

我正在做一個待辦事項的應用程序,與react-typescript-redux並想從我的服務器獲取todos。當我硬編碼待辦事項時,在我的容器中使用this.props.getTodos['todo1','todo2'],一切正常,但是當我嘗試異步執行時,使用this.props.requestTodos() - 事實並非如此。當我使用來自服務器的this.props.requestTodos()響應到達getTodos actionCreator時,但由於某種原因操作對象未到達簡化器,所以狀態不會更新。我該如何解決? actionCreators:當使用redux-thunk時,操作對象沒有到達reducer

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

} 

回答

3

你看上去調用getTodos(),但實際上沒有調度它。試試這個:

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

廢話,我忘了把它包裹在派送!現在它可以工作。謝啦。 – Umbrella

相關問題