1、目录结构
2、count/index.js
import React, {Component} from "react";
//引入store,用于获取数据
import store from '../../redux/store'
export default class Count extends Component {
state = {
count:store.getState()
}
componentDidMount() {
//监测redux中的数据的变化,只要改变,就会调用render
store.subscribe(()=>{
this.setState({
count:store.getState()
})
})
}
//加法
increment=()=>{
const {value} = this.selectNum
//通知redux 改变
store.dispatch({type:'increment',data:parseInt(value)})
}
//减法
decrement=()=>{
const {value} = this.selectNum
store.dispatch({type:'decrement',data:parseInt(value)})
}
//奇数加
incrementIfOdd=()=>{
const {value} = this.selectNum
const {count} = this.state
if(count%2!==0)
{
store.dispatch({type:'increment',data:parseInt(value)})
}
}
//异步加
incrementAsync=()=>{
const {value} = this.selectNum
const {count} = this.state
setTimeout(()=>{
store.dispatch({type:'increment',data:parseInt(value)})
},500)
}
render()
{
return(
<div>
<h1>当前求和为:{store.getState()}</h1>
<select ref={(c)=>this.selectNum=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.incrementIfOdd}>当前求和为奇数在加</button>
<button onClick={this.incrementAsync}>异步加</button>
</div>
);
}
}
3、redux/count_reducer.js
/*
1.该文件是用于创建一个为count服务的reducer,reducer的本质就是一个函数
2.reducer函数会接到两个参数,分别为:之前的状态(preState),动作对象(action)
*/
const initState = 0
export default function countReducer(preState=initState,action) {
console.log('countReducer',preState,action)
const {type,data} = action
// 根据type决定如何加工数据
switch (type){
case 'increment':
console.log('@')
return preState + data
case 'decrement':
return preState - data
default:
return preState
}
}
/redux/store.js
/*
该文件专门用于创建一个为Count组件服务的store对象
*/
//引入createStore,专门创建redux中最为核心的store对象
import {createStore} from 'redux'
//引入cunter.redux.js文件
import countReducer from './count_reducer'
//暴露store
export default createStore(countReducer)
4、src/app.js
import React, {Component} from "react";
import Count from "./components/Count";
export default class App extends Component {
render()
{
return(
<div>
<Count></Count>
</div>
);
}
}
5、src/index.js
import React from "react";
import ReactDOM from 'react-dom'
import App from './App'
ReactDOM.render(<App/>,document.getElementById('root'))