redux是JavaScript应用的状态容器,提供可预测花的状态管理。它保证程序行为一致性且易于测试。
1.安装redux
npm install redux -S
2.使用步骤
(1)需要一个store来存储数据
(2)store里的reducer初始化state并定义state修改规则
(3)通过dispatch一个action来提交对数据的修改
(4)action提交到reducer函数里,根据传入的action的type,返回新的state
3.代码示范
(1)创建store,src/store/index.js
import {createStore} from 'redux'
// reducer是纯函数
const counterReducer = (state=0,action)=>{
switch(action.type){
case 'ADD':
return state+1
case 'MINUX':
return state-1
default:
return state
}
}
const store = createStore(counterReducer)
export default store
(2)在page页面使用,reduxpage.js
import React,{Component} from 'react'
import store from '../store/index.js'
export default class ReduxPage extends Component {
componentDidMount(){
//第一种更新办法
store.subscribe(()=>{
this.forceUpdate()//强制刷新
})
}
render(){
return (
<div>
<p>{store.getState()}</p>
<button onClick={()=>store.dispatch({type:'ADD'})}>增加</button>
</div>
)
}
}
//第二种更新办法
在index.js中
import store from './store'
ReactDOM.render(<App/>,document.getElementById('root'))
store.subscribe(()=>{
ReactDOM.render(<App/>,document.getElementById('root'))
})