2017-11-11 54 views
0

我是React和Redux的新手,以前我只使用Angular。我嘗試使用Redux時,發生了學習React的第一個問題。我定義我的簡單的狀態,動作,減速並存儲在index.tsx文件:React,Redux和Typescript - 如何獲得這個工作

export interface AppState { 
    count: number; 
} 

const INCREMENT = 'INCREMENT'; 
export class IncrementAction implements Action { 
    type = INCREMENT; 
} 

function opsReducer(state: AppState = {} as AppState, action: IncrementAction): AppState { 
    console.log("ops reducer", action); 
    switch (action.type) { 
     case INCREMENT: 
      return { ...state, count: state.count + 1 } as AppState; 
     default: 
      return state; 
    } 
} 

const rootReducer = combineReducers({ 
    ops: opsReducer 
}); 

const store = createStore(rootReducer); 

ReactDOM.render(
    <Provider store={store}> 
     <App appName="Test" /> 
    </Provider>, 
    document.getElementById('root') as HTMLElement 
); 

而且修改應用程序組件,因此它是連接和看起來像

interface StateProps { 
    appName: string; 
} 

interface DispatchProps { 
    increment:() => void; 
} 

class App extends React.Component<StateProps & DispatchProps> { 
    render() { 
     return (
      <div className="App"> 
       <button onClick={this.props.increment}>CLICK ME {this.props.appName}</button> 
      </div> 
     ); 
    } 
} 

function mapDispatchToProps(dispatch: Dispatch<AppState>) { 
    return { 
     increment:() => dispatch(new IncrementAction()) 
    } as DispatchProps; 
} 

export default connect<StateProps, DispatchProps>(null, mapDispatchToProps)(App); 

有一個錯誤的index.tsx文件:

Type '{}' is not assignable to type 'Readonly<Pick<StateProps & DispatchProps, "appName">>'. 
Property 'appName' is missing in type '{}'. 

如何解決它?如何讓所有這些工作與TypeScript的硬打字工作?當我最終修復它時,如何組織源代碼?哪些東西應該移至分隔文件?我喜歡基於特徵的代碼分離。如何用React和Redux做到這一點?

回答

0

我覺得這裏的關鍵問題是function opsReducer。你說的類型stateAppState初始值空物體。相反{}這樣寫:

function opsReducer(state: AppState = { count: 0 }, action: IncrementAction): AppState { 
    console.log("ops reducer", action); 
    switch (action.type) { 
     case INCREMENT: 
      return { ...state, count: state.count + 1 }; 
     default: 
      return state; 
    } 
} 
相關問題