1.在使用前我们先安装
npm install redux -S
在文件中引入
2.import {createStore} from 'redux'
3.初始化 state数据
const defaultState ={
s:0,
a:0
}
4.创建reducer函数 第一个参数是 数据状态 第二个是action方法 且action必须有type属性
let reducer=(state=defaultState,action)=>{
switch(action.type){
case 'SUPPORT': //根据 action.type 进行那种操作
state={...state,s:state.s+1}
return state; // 操作完成之后 返回 操作后的 state数据
case 'AGAINST':
state={...state,a:state.a+1}
console.log(state);
return state;
default:
return state;
}
}
5.创建容器
// 返回一个容器 且这个容器会有三个方法,dispatch,subscrible,getstate
let store=createStore(reducer)
6.在组件中使用 情况
this.state=this.props.store; // 可以赋值到 state上面
let {getState} =this.props.store; // 也可以结构里面的数据 进行展示
let {s=0,a=0}=getState();
// 下面是绑定在按钮上 进行事件处理 更改 state中的数值
<div className="card-footer">
<button className="btn btn-primary" onClick={()=>{
this.props.store.dispatch({type:'SUPPORT'})
}}>支持</button>
<button className="btn btn-danger ml-2" onClick={()=>{
this.props.store.dispatch({type:'AGAINST'})
}}>反对</button>
</div>
// 每次更改数据 在 生命周期函数中 重新渲染 页面 数据 使页面上的数据发生变化
componentDidMount=()=>{
this.props.store.subscribe(()=>{
this.setState(this.props.store.getState())
})
}