1.redux搭建
安装redux
yarn add redux
2.store
//该文件用于暴露store对象
//引入createStore,专门用于创建redux中最核心的store对象
import {createStore} from 'redux'
//引入为count组件服务的reducer
import countReducer from './count_reducers'
//store中需要一个为之服务的reducer,因此将引入的reducer当参数传入这个创建的store中
//并且将这个store对象暴露出去
export default createStore(countReducer)
3.reducer
//创建一个为组件服务的reducer,它的本质是一个函数
//定义个初始值
let initState=0
//传入两个参数,一个为之前的状态preState,另一个是动作对象action
//设置默认值,初始化数据data
//这里的reducer是一个纯函数
export default function countReducers(preState =initState, action) {
//从action中拿到type与data
const {
type,
data
} = action
//根据type加工数据
switch (type) {
case 'increment':
return preState + data
case 'decrement':
return preState - data
default:
return preState
}
}
4.action
//分别封装两个action函数用来创建action对象
export const createIncrement=data=>({type:"increment",data})
export const createDecrement=data=>({type:"decrement",data})
5.constant
//定义常量文件
export const INCREMENT='increment'
export const DECREMENT='decrement'
6.使用
6.1 引入store
import store from '../../redux/count_redux/store'
6.2通过getstate可以获取初始状态
<h1>当前显示的数是:{store.getState()}</h1>
6.4引入action
import {createIncrement,createDecrement} from '../../redux/count_redux/count_action'
6.3使用dispatch去传递action
//通知redux去加value
store.dispatch(createIncrement(value*1))
6.4渲染render
因为没有setdata,页面没有发生更新,需要监听redux,动态的去触发render函数
使用setstate中去触发render
componentDidMount(){
store.subscribe((()=>{
this.setState({})
}))
}
重新渲染根组件,触发render
store.subscribe(()=>{
ReactDOM.render(
<App />,
document.getElementById('root')
);
})
7.案例
import React, { Component } from 'react'
// 引入store用于获取store状态
import store from '../../redux/count_redux/store'
import {createIncrement,createDecrement} from '../../redux/count_redux/count_action'
export default class index extends Component {
componentDidMount(){
store.subscribe((()=>{
this.setState({})
}))
}
//加
increment=()=>{
let {value}=this.selectNumber
//通知redux去加value
store.dispatch(createIncrement(value*1))
}
//减
decrement=()=>{
let {value}=this.selectNumber
//通知redux去加value
store.dispatch(createDecrement(value*1))
}
//异步加
asyncIcrement=()=>{
let {value}=this.selectNumber
setTimeout(() => {
store.dispatch(createIncrement(value*1))
}, 500);
}
//奇数加
oddIcrement=()=>{
let {value}=this.selectNumber
let count=store.getState()
if(count%2!==0){
store.dispatch(createIncrement(value*1))
}
}
render() {
return (
<div>
<h1>当前显示的数是:{store.getState()}</h1>
<select ref={c=>this.selectNumber=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.asyncIcrement}>异步加</button>
<button onClick={this.oddIcrement}>奇数加</button>
</div>
)
}
}