Redux+Typescript 通过加减器demo来了解redux

198 阅读2分钟

首先UI部分最简洁的就是需要三个部分,一个显示数字的地方,两个按钮分别对应加减,同时我们用typescript来代替Propstype进行类型检测。

import React from 'react'
export interface Iprops{
  value:number;
  onIncrement:()=>void;
  onDecrement:()=>void;
}

const Counter = ({value,onIncrement,onDecrement}:Iprops):JSX.Element=> {
  return(
    <p>
      Clicked: {value}
      <br/>
      <br/>
      <br/>
      <button onClick={onIncrement} style={{marginRight:20}}> + </button>
      <button onClick={onDecrement} > - </button>
    </p>
    
  )
}

export default Counter

下面主要说redux部分如何设计: 大方向来说我们需要actions来下达命令,需要reducers来执行,当然我们还得定义我们需要的state 这里显然state里就一个值,而且类型是数值类型

	export type StoreState = number

然后设计actions src下创建一个actions文件夹,并创建一个index.tsx,这里我们主要涉及的操作就是加减,所以我们需要定义加减的行为,一定要记住action只是下达命令,告诉reducer来做什么操作,比如做加法的时候,我们就指定当前type:INCREMENT,

export interface INCREMENTAction{
  type:INCREMENT
}
export interface DECREMENTAction{
  type:DECREMENT
}
export type ModifyAction = INCREMENTAction | DECREMENTAction

然后我们使用action创建函数来生成action

export const increment = ():INCREMENTAction=>({type:INCREMENT})
export const decrement = ():DECREMENTAction=>({type:DECREMENT})

然后编写具体的逻辑,src下创建reducers/index.tsx,

reducer接受两个参数,一个state,一个action

而且类型也很好推断,state就是一个number类型的值并且我们默认初始值为0,然后action的类型就是上面的ModifyAction,可加可减,当然最后的返回值也是和state类型一样的数值类型

	export default (state = 0,action:ModifyAction):number=>{
  switch (action.type) {
    case INCREMENT:
      return state+1
    case DECREMENT:
      return state-1
    default:
      return state
  }
}

而且一定要注意reducer是一个纯函数,也就是我们不能在原state上进行修改

现在store部分我们基本完成,现在我们需要将store和组件进行关联,所以我们来创建容器组件来架起二者之间的桥梁

主要借助connect mapStateToProps mapDispatchToProps 来创建

  • mapStateToProps: 将store里的数据以我们组件需要的形式传递到组件
  • mapDispatchToProps: 利用dispatch函数 创建props回调将action传入store
// 将 reducer 中的状态插入到组件的 props 中
const mapStateToProps = (state: StoreState): { value: number } => ({
    value: state
})

// 将 对应action 插入到组件的 props 中
const mapDispatchToProps = (dispatch: Dispatch) => ({
    onDecrement: () => dispatch(decrement()),
    onIncrement: () => dispatch(increment())
})

// 使用 connect 高阶组件对 Counter 进行包裹
export default connect(mapStateToProps, mapDispatchToProps)(Counter);

最后我们需要在index.tsx上创建store

引入redux的createStore,引入我们的reducer函数,来创建,另外我们引入Provider,并且传入store来让我们我的子组件都可以访问到store, 然后在App.tsx引入我们的容器组件

import React from 'react';
import CountCon from './container/CounterCon'


function App() {
  return (
   <div className='App'>
     <CountCon/>
   </div>
  )
}

export default App;