案例图:
纯react方法
redux文件
store.js
// 暴露store对象,整个应用只有一个store对象
// 引入createStore,专门用于创建redux中最为核心的store对象
import {createStore} from "redux"
import countReducer from "./count_reducer"
// 暴露store
export default createStore(countReducer)
count_reducer.js
// 编写函数【求和案例】
// 初始化
const initSetstate = 88
export default function countReducer(preState = initSetstate, action) {
console.log(preState,action)
// 从action对象中获取:type、data
const { type, data } = action
// type要与switch中相一致
switch (type) {
case 'increment': //+
return preState + data
case 'decrement': //-
return preState - data
default:
return preState
}
}
App.js
import React, { Component } from 'react'
import Count from './components/Count'
export default class App extends Component {
render() {
return (
<div>
<Count />
</div>
)
}
}
index.js
import React, { Component } from 'react'
import store from "../../redux/store"
export default class Count extends Component {
// 加+
increase = () => {
const { value } = this.selectNumber //解构赋值
// dispatch:分发 里面为action对象
store.dispatch({
type: 'increment',
data: value * 1
})
}
// 减-
decrease = () => {
const { value } = this.selectNumber
store.dispatch({
type: 'decrement',
data: value * 1
})
}
// 奇数加
increaseIfOdd = () => {
const { value } = this.selectNumber
const count = store.getState() //该对象为数值型,不需要解构赋值
if (count % 2 !== 0) {
store.dispatch({
type: 'increment',
data: value * 1
})
}
}
// 异步加 (700毫秒)
insAsync = () => {
const { value } = this.selectNumber
setTimeout(() => {
store.dispatch({
type: 'increment',
data: value * 1
})
}, 700)
}
render() {
return (
<div>
<h2>当前求和结果:{store.getState()}</h2>
<select ref={c => this.selectNumber = c}>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select><br />
<button onClick={this.increase}>+</button><br />
<button onClick={this.decrease}>-</button><br />
<button onClick={this.increaseIfOdd}>奇数加</button><br />
<button onClick={this.insAsync}>异步加</button><br />
</div>
)
}
}
解释说明
redux与纯react之间转换:
(1).去除Count组件自身的状态
(2).src下建立:
-redux
-store.js
-count_reducer.js
(3).store.js:
1).引入redux中的createStore函数,创建一个store
2).createStore调用时要传入一个为其服务的reducer
3).记得暴露store对象
(4).count_reducer.js:
1).reducer的本质是一个函数,接收:preState,action,返回加工后的状态
2).reducer有两个作用:初始化状态,加工状态
3).reducer被第一次调用时,是store自动触发的,
传递的preState是undefined,
传递的action是:{type:’@@REDUX/INIT_a.2.b.4}
(5).在index.js中监测store中状态的改变,一旦发生改变重新渲染
备注:redux只负责管理状态,至于状态的改变驱动着页面的展示,要靠我们自己写。