2017-11-11 23 views
0

Ich bin neu in React und Redux, vorher habe ich nur Angular benutzt. Mein erstes Problem beim Lernen von React trat auf, als ich versuchte, Redux zu verwenden. Ich habe meine einfachen Zustand, Aktion, Druckminderer und Speicher in index.tsx-Datei definiert:React, Redux und Typescript - wie funktioniert das?

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

und App-Komponente so modifiziert, dass sie verbunden ist und sieht aus wie dieser

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

Es ist ein Fehler auf index.tsx Datei:

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

Wie es zu beheben? Wie kann man all diese Sachen mit TypeScripts hartem Tippen arbeiten? Wenn ich es endlich repariere, wie organisiere ich Quellcode? Welche Dinge sollten in getrennte Dateien verschoben werden? Ich mag die Feature-basierte Codetrennung. Wie geht das mit React und Redux?

Antwort

0

Ich denke, das Schlüsselproblem ist hier function opsReducer. Sie sagten, der Typ state ist AppState und Anfangswert ist ein leeres Objekt. Stattdessen {} schreiben Sie es so:

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; 
    } 
} 
Verwandte Themen