react+react-redux+typescripte 之简单计数器

  • Post author:
  • Post category:其他


//compment
import React from 'react'
import { connect } from 'react-redux'
import store from '../../store'
import { TestAction } from '../../actions'
interface IProp{
  value:number,
  dispath: any
}
 class Home extends React.Component<IProp>{

  handleOnclick = () => {
    let {value} = this.props
    value+=1
    const action  = TestAction(value)
    this.props.dispath(action)
    console.log(this.props)
  }

  render(){
    return (
      <div>
        <div>{store.getState().value}</div>
        <button onClick = { this.handleOnclick }>点击我</button>
      </div>
      
    )
  }
}

const mapStateToProps = (state:any)=>{
    const { value } = state
    return {
      value
    }
}


const mapDispatchToProps = (dispath:any) =>{
  return {
    dispath
  }
}

export default connect(mapStateToProps,mapDispatchToProps)(Home)
//reducer
import { Action } from '../actions/index'

const initState = {
  value: 1
}

export function reducer(state = initState,action:Action){
  if(action.type === 'TestAction'){
      state.value = action.value
      return Object.assign({},state)
  }else{
    return state
  }
}
//action
export interface Action{
  type:string,
  value: any
}

export function TestAction(val:any):Action{
  return {
    type: 'TestAction',
    value: val
  }
}



版权声明:本文为love_life_forever原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。