redux使用,相当于vue中的vuex

实现上述功能:

下载redux, npm install redux

新建一个redux文件夹,里面新建一个count_reduce.js和store.js文件

count_reduce.js

复制代码
export default function count(pre=0,action){
    let {type,data} =action
    console.log(action,'action')

    switch(type){
        case 'increment':
        return pre+data;
        case 'decrement':
            return pre-data;
        default :
        return pre
    }
}

store.js

复制代码
// 该文件专门用于暴露一个store对象,整个应用只有一个store对象

//引入redux
import { legacy_createStore as createStore } from "redux";
import reducer from './count_reducer'
const store =createStore(reducer)
export default store

页面使用

复制代码
import React, { Component } from 'react'
import store from '../../redux/store';
export default class index extends Component {
    //这块主要因为redux不会渲染render,所以在这里监听store值的改变
    componentDidMount(){
        store.subscribe(()=>{
            this.setState({})
        })
    }
    // 相加
    increment=()=>{
        let {value} =this.selectVal;
        store.dispatch({type:'increment',data:value*1})
    }
    // 相减
    decrement=()=>{
        let {value} =this.selectVal;
        store.dispatch({type:'decrement',data:value*1})
    }
    // 为奇数加加
    incrementOdd=()=>{
        let {value} =this.selectVal;
        let count =store.getState();
        if(count % 2!==0){
        store.dispatch({type:'increment',data:value*1})
        }
    }
    // 等一会加加
    incrementWait=()=>{
        let {value} =this.selectVal;
        setTimeout(() => {
            store.dispatch({type:'increment',data:value*1})
        }, 500);
    }
  render() {
    return (
      <div>
        <h2>和为:{store.getState()}</h2>
        <select ref={e=>this.selectVal=e}>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
        </select>&nbsp;
        <button onClick={this.increment}>+</button>&nbsp;
        <button onClick={this.decrement}>-</button>&nbsp;
        <button onClick={this.incrementOdd}>和为奇数时再加</button>&nbsp;
        <button onClick={this.incrementWait}>等一等再加</button>&nbsp;
      </div>
    )
  }
}
相关推荐
开开心心就好31 分钟前
批量提取PDF中的图片,直接导出原图
前端·javascript·支持向量机·智能手机·pdf·html·启发式算法
Setsuna_F_Seiei3 小时前
前端转型 Agent 开发 05 之 Agent Hooks 与 Checkpointer(让 Agent 从全自动转变人为可掌控)
前端·agent·ai编程
百万蹄蹄向前冲5 小时前
风扇转了一晚上MVP专家团翻车事故
前端·人工智能
默_笙5 小时前
🏛 给 AI 配一间办公室:Harness Engineering 六大模块与它的实现
前端·javascript
linux_cfan6 小时前
videojs v10 源代码系列解读:14 · 谓词守卫:在运行时安全地调用能力
前端·javascript·音视频
kyriewen6 小时前
我扒了 10,221 条 JD:腾讯技术岗 75% 在要 AI
前端·人工智能·ai编程
郑州光合科技余经理7 小时前
同城外卖小程序开发:下单成功后,后台导出能不能对上用户端状态
开发语言·前端·git·后端·uni-app·php·ai编程
+VX:Fegn08958 小时前
计算机毕业设计|基于springboot + vue旅游管理系统(源码+数据库+文档)
java·开发语言·vue.js·spring boot·课程设计
雪芽蓝域zzs8 小时前
第 7 章:双 Y 轴组合图(柱状 + 折线,看板高频场景)
vue.js·echars
IT_陈寒8 小时前
Vue的响应式让我熬到凌晨三点,原来漏了这个小细节
前端·人工智能·后端