安装

  1. npm i --save redux

配置状态

新建 reducer.js 状态管理文件

  1. // state
  2. const state = {
  3. // 存储公共状态数据
  4. },
  5. export default (state,action)=>{
  6. return state
  7. }

新建 store/index.js 文件 状态管理工具

  1. // 生成状态管理模块
  2. import {createStore} from 'redux'
  3. import reducer from './reducer.js '
  4. const store = createStore(reducer)
  5. // 导出
  6. export default store

在组件中使用

  1. // 导入 store
  2. import store from './store/index.js'
  3. // 获取全部状态
  4. store.getState()

修改状态

  1. // 在事件处理程序中建立action
  2. const action = {
  3. type:'自定义名字',
  4. value:新的值
  5. }
  6. // 传递action
  7. store.dispatch(action)

reducer.js 文件 接收action

  1. // reducer 只能接收action 不能改变state
  2. export default (state,action)=>{
  3. // state 状态值
  4. // action 接收的action
  5. if(action.type==='名字'){
  6. // 改变state的方法
  7. let newState = JSON.parse(JSON.stringfy(state))
  8. newState.XXX = action.value
  9. // 重新传递state为newstate
  10. return newState
  11. }
  12. return state
  13. }

在中间中订阅状态

  1. // 生命周期钩子函数
  2. constructor(){
  3. store.subscribe(this.storeChange)
  4. }
  5. // 订阅方法
  6. const storeChange ()=>{
  7. this.setState(store.geState())
  8. }

代码优化

新建 action.js 文件 统一存储type 消除魔法字符串

  1. // 集中报错 action 的type值
  2. export const 名字全大写 = 'type值'
  3. // 组件中使用 引入常量type值
  4. 使用这写变量替换type
  5. // reducer.js 中
  6. 引入常量值 替换其中的字符串

新建文件 封装action

  1. // 返回一个action对象 传入type 和 value
  2. const XXXX = (type,value) => {
  3. return {
  4. type,
  5. value
  6. }
  7. }