2017-11-11 3 views
0

以前はReactとReduxを初めて使用しましたが、これまではAngularのみを使用していました。私がReduxを使用しようとしたときにReactを学ぶことに私の最初の問題が発生しました。それが接続されており、そのReact、Redux、Typescript-この作業を行うには

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上の誤りがあり

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

とアプリのコンポーネントを修正:私は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だと思います。 stateのタイプがAppStateであり、初期値の空のオブジェクトであると答えました。代わりに{}のように書く:

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; 
    } 
} 
関連する問題