2017-11-11 21 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; 
    } 
} 
相关问题