创建项目
npx create-react-app 项目名称 --typescript
yarn create react-app 项目名称 --typescript
安装redux
yarn add redux react-redux
添加react-redux的类型声明文件
yarn add @types/react-redux -D
添加redux的action的类型
export interface Action {
type: string;
...
}
export function contReducer(state, action:Action) {
switch(action.type) {
case 'xxx':
return xxx
default :
return state
}
}
添加redux的reducer的类型声明
import { combineReducers, createStore } from 'redux'
import { contReducer } from './reducer'
const rootReducer = combineReducers() {
count:contReducer
}
export default function configureStore () {
const store = createStore(rootReducer)
return store
}
在index.tsx中使用redux
// ------------------------index.tsx
import React from 'react'
import ReactDOM from 'react-dom'
import {Provider} from 'react-redux'
import configureStore from './store'
import App from './App'
const store = configureStore()
React.render((
<Provider store={store}>
<App/>
</Provider>
),document.getElementById('root'))
在App中调用redux的action
// ---------------------------store
export type AppStore = ReturnType<typeof rootReducer>
// ----------------------------App.ts
import React, {Componet} from 'react'
import {connect} from 'react-redux'
import {addCount} from './store/actions'
import {AppStore} from './store'
interface IAppProps {
count: number;
addCount: typeof addCount
}
class App extends Component<IAppProps, {}> {
render () {
return (
<div className="app">
</div>
)
}
}
const mapStateToProps = (state:AppStore) => ({count: state})
export default connect(mapStateToProps, {addCount})(App)