实现上述功能:
下载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>
<button onClick={this.increment}>+</button>
<button onClick={this.decrement}>-</button>
<button onClick={this.incrementOdd}>和为奇数时再加</button>
<button onClick={this.incrementWait}>等一等再加</button>
</div>
)
}
}