当前位置: 首页 > news >正文

一个redux使用案例模板

目录

redux

纯函数和高阶函数:

 redux 开发工具使用

react-redux


redux

1. 结构:

 count--index.jsx

import React, { Component } from 'react'
import store from '../../redux/store'
import { acDecrement,acIncrement,acAsyncIncrement } from '../../redux/count_action'

export default class Count extends Component {

  state = {count:0}
  // store 里面的数据法神变化,更新页面
  componentDidMount(){
    store.subscribe(()=>{
      this.setState({})
    })
  }
  increment = ()=>{
    let value = this.selectRef.value
    store.dispatch(acIncrement(value*1))
  }
  decrement = ()=>{
    let value = this.selectRef.value
    store.dispatch(acDecrement(value*1))
  }
  handleOdd = ()=>{
    let value = this.selectRef.value
    if(store.getState() % 2 !== 0) store.dispatch(acIncrement(value*1))

  }
  handleAsync = ()=>{
    let value = this.selectRef.value
    // let count = this.state.count
    // setTimeout(()=>{
    //   store.dispatch(acIncrement(value*1))
    // },500)

    store.dispatch(acAsyncIncrement(value*1,500))
  }


  render() {
    // console.log(this)
    return (
      <div>
        <h1>当前求和{store.getState()}</h1>
        <select ref={c =>this.selectRef = c}>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
        </select>

        <button onClick={this.increment}>+</button>
        <button onClick={this.decrement}>-</button>
        <button onClick={this.handleOdd}>奇数+</button>
        <button onClick={this.handleAsync}>异步+</button>
      </div>
    )
  }
}

redux--store.js

import {legacy_createStore as createStore,applyMiddleware} from 'redux'
// 创建store需要引入为redux服务的reducer
import reducer from './count_reducer'

// 引入 异步action 需要的中间件 thunk ,通过applyMiddleware使用此中间件
import thunk from 'redux-thunk'


//暴露store
export default createStore(reducer,applyMiddleware(thunk))

redux--reducer.js

// 就是一个函数
// 接收两个参数: preState 和 action

let initCount = 5
export default function countReducer(preState=initCount,action) {
  // console.log(preState,'preState')
  let {data,type} = action
  switch(type) {
    case 'increment': return preState+data
    case 'decrement': return preState-data
    default: return preState
  }
}

redux--action.js

// 就是个函数
// 同步action 返回对象,异步action 返回对象

// 异步action 需要中间件 redux-thunk

export const acIncrement = data=>({type:'increment',data})
export const acDecrement = data=>({type:'decrement',data})
export const acAsyncIncrement = (data,time)=>{
  return (dispatch)=>{
    setTimeout(()=>{
      dispatch(acIncrement(data))
    },time)
  }
}

纯函数和高阶函数:

 redux 开发工具使用

在谷歌中导入文件夹(需要下载)

react-redux

 1. 结构:

containers--count.jsx

import React, { Component } from 'react'
import { connect } from "react-redux";
import {acDecrement,acAsyncIncrement,acIncrement} from '../../redux/count_action'

class CountUI extends Component {

  state = {count:0}
  // store 里面的数据法神变化,更新页面
  // componentDidMount(){
  //   store.subscribe(()=>{
  //     this.setState({})
  //   })
  // }
  increment = ()=>{
    let value = this.selectRef.value
    this.props.PropIncrement(value*1)
  }
  decrement = ()=>{
    let value = this.selectRef.value
    this.props.PropDecrement(value*1)
  }
  handleOdd = ()=>{
    let value = this.selectRef.value
    if(this.props.count % 2 !==0) {
      this.props.PropIncrement(value*1)
    }

  }
  handleAsync = ()=>{
    let value = this.selectRef.value
    this.props.PropAsyncIncrement(value*1,500)
  }


  render() {
    // console.log(this)
    return (
      <div>
        <h1>当前求和{this.props.count}</h1>
        <select ref={c =>this.selectRef = c}>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
        </select>

        <button onClick={this.increment}>+</button>
        <button onClick={this.decrement}>-</button>
        <button onClick={this.handleOdd}>奇数+</button>
        <button onClick={this.handleAsync}>异步+</button>
      </div>
    )
  }
}

export default connect(
  (state)=>({
    count:state.reducerCount
  }),
  // api 优化
  {
    PropIncrement:acIncrement,
    PropDecrement:acDecrement,
    PropAsyncIncrement: acAsyncIncrement,
  }

  /* (dispatch)=>({
    PropIncrement: (data) => dispatch(acIncrement(data)),
    PropDecrement: (data) => dispatch(acDecrement(data)),
    PropAsyncIncrement: (data,time) => dispatch(acAsyncIncrement(data,time)),
  }) */
)(CountUI)

 ------person.jsx

import React, { Component } from 'react'
// import store from '../../redux/store'


// 使用 store 里面的共享数据
import { connect } from 'react-redux'

class PersonUI extends Component {
  render() {
    return (
      // <div>PPindex{store.getState().reducerCount}</div>
      <div>PPindex{this.props.reducerCount}</div>
    )
  }
}

// 自动检测store 里面的数据发生变化,然后自动更新页面
export default connect(
  (state)=>({
    reducerCount: state.reducerCount
  }),
  {}
)(PersonUI)

 redux---reducer.js和action.js  (不变)

// 就是一个函数
// 接收两个参数: preState 和 action

let initCount = 5
export default function countReducer(preState=initCount,action) {
  // console.log(preState,'preState')
  let {data,type} = action
  switch(type) {
    case 'increment': return preState+data
    case 'decrement': return preState-data
    default: return preState
  }
}



//action
// 就是个函数
// 同步action 返回对象,异步action 返回对象

// 异步action 需要中间件 redux-thunk

export const acIncrement = data=>({type:'increment',data})
export const acDecrement = data=>({type:'decrement',data})
export const acAsyncIncrement = (data,time)=>{
  return (dispatch)=>{
    setTimeout(()=>{
      dispatch(acIncrement(data))
    },time)
  }
}

------store.js

import {legacy_createStore as createStore,applyMiddleware, combineReducers} from 'redux'
// 创建store需要引入为redux服务的reducer
import reducerCount from './count_reducer'

// 引入 异步action 需要的中间件 thunk ,通过applyMiddleware使用此中间件
import thunk from 'redux-thunk'

//合并reudcer 需要 combineReducers
//汇总最好直接写在 reducer 文件夹里面的index.js中
const allReducer = combineReducers({
  reducerCount: reducerCount,
})
//暴露store
export default createStore(allReducer,applyMiddleware(thunk))

App.jsx

import React, { Component } from 'react'
import Count from './containers/count'
import Person from './containers/person'


export default class App extends Component {
  render() {
    return (
      <div>
        <Count />
        <Person />
      </div>
    )
  }
}

index.js

import React from "react";
import ReactDOM from "react-dom";
import App from './App'
import store from './redux/store'
import {Provider} from 'react-redux'

ReactDOM.render(
  <Provider store={store}>
    <App/>
  </Provider>
  ,document.getElementById('root')
) 

// 用react-redux 不用再手动检测
// store.subscribe(()=>{
//   ReactDOM.render(<App/>,document.getElementById('root')) 
// })

相关文章:

  • 超详细的水果FL Studio21最新版更新全功能详细介绍!80项更新与改进!
  • CENTOS上的网络安全工具(十四)搬到Docker上(2)?
  • 微服务框架 SpringCloud微服务架构 21 RestClient 操作文档 21.1 新增文档
  • APP自动化测试系列之Appium介绍及运行原理
  • Nginx学习笔记
  • 蜣螂优化算法Dung beetle optimizer附matlab代码
  • 03-SpringBoot进阶
  • 英文Paper写作怎么确实合适的介词?
  • 代码提速100倍,怎么实现的?
  • 【C++】C++11新特性
  • 【面试】EntityFrameworkLinq面试题答案
  • 宝塔部署node项目
  • 配对交易之统计套利配对:协整(cointegration)
  • [附源码]Python计算机毕业设计Django演唱会门票售卖系统
  • [附源码]计算机毕业设计快转二手品牌包在线交易系统Springboot程序
  • 一个支持 CRUD 快速开发的 Web 框架,用着太爽
  • 2小时开发《点球射门游戏》,动画演示思路(上),代码已开源
  • 【Opencv实战】颜色测试:你是色盲/色弱吗?从零带你了解色彩与原理,简单的颜色识别小程序,感动.jpg(全是干货)
  • windows服务开发
  • leetcode-每日一题-二进制表示中质数个计算置位(简单,popcount算法)
  • 电加热油锅炉工作原理_电加热导油
  • 大型电蒸汽锅炉_工业电阻炉
  • 燃气蒸汽锅炉的分类_大连生物质蒸汽锅炉
  • 天津市维修锅炉_锅炉汽化处理方法
  • 蒸汽汽锅炉厂家_延安锅炉厂家
  • 山西热水锅炉厂家_酒店热水 锅炉
  • 蒸汽锅炉生产厂家_燃油蒸汽发生器
  • 燃煤锅炉烧热水_张家口 淘汰取缔燃煤锅炉
  • 生物质锅炉_炉
  • 锅炉天然气_天燃气热风炉