已解决
redux使用,相当于vue中的vuex
来自网友在路上 150850提问 提问时间:2023-09-21 09:46:03阅读次数: 50
最佳答案 问答题库508位专家为你答疑解惑
实现上述功能:
下载redux, npm install redux
新建一个redux文件夹,里面新建一个count_reduce.js和store.js文件
count_reduce.js
export default function count(pre=0,action){let {type,data} =actionconsole.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> <button onClick={this.increment}>+</button> <button onClick={this.decrement}>-</button> <button onClick={this.incrementOdd}>和为奇数时再加</button> <button onClick={this.incrementWait}>等一等再加</button> </div>)}
}
查看全文
99%的人还看了
相似问题
猜你感兴趣
版权申明
本文"redux使用,相当于vue中的vuex":http://eshow365.cn/6-10610-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!
- 上一篇: Linux安全加固:保护你的服务器
- 下一篇: 绘图系统四:定制绘图风格