React学习笔记08

发布于:2025-03-02 ⋅ 阅读:(97) ⋅ 点赞:(0)

一、什么是Redux

Redux是React中最常用的集中状态管理工具,类似于Vue中的Pinia(Vuex),可以独立于框架运行,作用是通过集中管理的方式管理应用的状态

二、Redux快速体验

手搓一个Redux:

1、定义一个reducer函数(根据当前想要做的修改返回一个新的状态)

2、使用createStore方法传入reducer函数生成一个store实例对象

3、使用store实例的subscribe方法订阅数据的变化(数据一旦发生变化,可以得到通知)

4、使用store实例dispatch方法提交action对象触发数据变化(告诉reduce你想怎么改数据)

5、使用store实例的getState方法获取最新的状态数据更新到视图中

// 1.定义reducer函数
// 作用:根据不同的action对象,返回不同的新的state
// state:管理的数据初始状态
// action:对象type标记当前想要做什么样的修改
const Redux = useReducer()
function reducer(state = { count: 0 }, action) {
  // 数据不可变:基于原始状态生成一个新的状态
  if (action.type === 'INCREMENT') {
    return { count: state.count + 1 }
  }
  if (action.type === 'DECREMENT') {
    return { count: state.count - 1 }
  }
  return state
}
// 2.使用reducer函数生成store实例
const store = Redux.createStore(reducer)

// 3.通过store实例的subscribe订阅数据变化
store.subscribe(() => {
  console.log('state变化了', store.getState());
  // 5.通过store实例的getState方法
  document.getElementById('count').innerText = store.getState().count
})

// 4.通过store实例的dispatch函数提交action更改状态
const inBtn = document.getElementById('increment')
// 增
inBtn.addEventListener('click', () => {
  store.dispatch({
    type: 'INCREMENT'
  })
})

const dBtn = document.getElementById('decrement')
// 减
dBtn.addEventListener('click', () => {
  store.dispatch({
    type: 'DECREMENT'
  })
})

三、Redux管理数据流程梳理

为了职责清晰,数据流向明确,Redux把整个数据修改的流程分成了三个核心概念,分别是state、action和reducer

1.state:一个对象,用来存放我们管理的数据状态

2.action:一个对象,用来描述你想怎么改数据

3.reducer:一个函数,用来根据action的描述生成一个新的state

至此Redux快速上手介绍完了,敬请关注下一章Redux与React