2017-01-20 33 views
2

我很難用redux和typescript創建商店。這是actions.js:無法在TypeScript + Redux中使用Reducer創建商店

import { Action } from 'redux'; 

export interface ITodoAction extends Action { 
    todo:string; 
} 

export const ADD_TODO:string = 'ADD_TODO'; 
export function addTodo(todo:string):ITodoAction { 
    return { 
     type: ADD_TODO, 
     todo 
    }; 
} 

我出口接口名爲ITodoAction,爲我的自定義屬性的待辦事項擴展行動自定義操作:字符串。

這是reducers.js:

import { Reducer } from 'redux'; 
import { ITodo } from '../interfaces'; 
import { ITodoAction, ADD_TODO } from '../actions'; 

let id:number = 0; 
const generateId =():number => id++; 

interface ITodoState { 
    todos:Array<ITodo> 
}; 

const defaultState:ITodoState = { 
    todos: [] 
}; 

export function todoReducer(state:ITodoState = defaultState, action:ITodoAction):ITodoState { 
    switch(action.type) { 
     case ADD_TODO: 
      return Object.assign({}, state, { 
       todos: [ 
        { id: generateId(), text: action.todo, completed: false }, 
        ...state.todos 
       ] 
      }); 
     default: 
      return state; 
    } 
} 

我用ITodoAction從以前actions.js FIR定義todoReducer。 todoReducer將返回ITodoState情況下,它看起來像:

{ 
    type: 'ADD_TODO', 
    todos: [ ITodo{}, ITodo{}, ITodo{}, ... ] 
} 

這是ITodo接口,我是用:

export interface ITodo { 
    id:number; 
    todo:string; 
    completed:boolean; 
} 

它包含ID,文本,完成只是普通的對象。我覺得這好像很好,但是當我試圖創建存儲與這樣的減速機:

import { createStore } from 'redux'; 
import todoReducer from './reducers'; 

export const store = createStore(todoReducer); 

它失敗:

Argument of type 'typeof "/.../typescript-todo/src/ts/reducers/index"' is not assignable to parameter of type 'Reducer<{}>'... 
Type 'typeof "/./typescript-todo/src/ts/reducers/index"' provides no match for the signature '&lt;A extends Action&gt;(state: {}, action: A): {}' 

貌似我解決我的減速,但是我沒有得到它如何使用Reducer < {} >定義reducer,我每次嘗試失敗時都會收到類似的消息,如「blablabla不能分配給blablabla」。

我想要的只是使用我簡單的減速器,但爲什麼我不能? 它不會與combineReducer一起工作,在這個時候,它需要使用某種ReducerMap或什麼,我不記得實際的接口是什麼。

我發現很多打字稿+ Redux的相關帖子,但喜歡的事,他們只是用他們自己定義的動作和減速,他們沒有使用減速< {} >或行動>牛逼<,但這些都只是做我混淆了,爲什麼他們沒有使用Reducer和Action界面,爲什麼它工作?

不知怎的,我發現了終極版的類型聲明,這是怎麼減速< {} >樣子:

export type Reducer<S> = <A extends Action>(state: S, action: A) => S; 

儘可能我可以理解爲減速< {} >是一個返回函數州。那麼爲什麼我的todoReducer不與他們合作?我試過用Reducer <ITodoState>,但它不起作用。

我現在真的很困惑,看起來我錯過了一些大事,但是,哇,我真的不明白我錯過了什麼。 我從來沒有想過用TypeScript使用Redux可能很難。

我盡力了,但看起來像我需要一隻手。任何建議將非常感激。

+0

我遇到了同樣的問題。你有沒有找到任何決議? –

+0

@ erik-sn其實是的,只是改變導出函數todoReducer導出默認函數todoReducer和它的工作。 – modernator

回答

1

固定,只是出口減速機作爲默認值,它的工作。