官网:https://redux.js.org/introduction/getting-started

(Redux 官网对 Redux 知识的讲解有很多重复的地方,所以学习的时候要懂得挑重点看)

一、Getting Started

1. 安装 React Toolkit 和 Redux

一进入 Redux 介绍页,它就极力推荐使用 React Toolkit 写 Redux 逻辑。我觉得要先了解 Redux 核心内容,再去学习使用 React Toolkit 更好。
(我不用 React Toolkit,觉得它增加了使用 Redux 的心智负担)

安装 React Toolkit

  1. yarn add @reduxjs/toolkit

安装 Redux

  1. yarn add redux

2. 两个例子

一个简单的 Redux 例子

  1. import { createStore } from 'redux'
  2. function counterReducer(state = { value: 0 }, action) {
  3. switch (action.type) {
  4. case 'counter/incremented':
  5. return { value: state.value + 1 }
  6. case 'counter/decremented':
  7. return { value: state.value - 1 }
  8. default:
  9. return state
  10. }
  11. }
  12. let store = createStore(counterReducer)
  13. store.subscribe(() => console.log(store.getState()))
  14. store.dispatch({ type: 'counter/incremented' })
  15. store.dispatch({ type: 'counter/incremented' })
  16. store.dispatch({ type: 'counter/decremented' })

一个使用 Redux Toolkit 的例子

  1. const counterSlice = createSlice({
  2. name: 'counter',
  3. initialState: {
  4. value: 0
  5. },
  6. reducers: {
  7. incremented: state => {
  8. state.value += 1
  9. },
  10. decremented: state => {
  11. state.value -= 1
  12. }
  13. }
  14. })
  15. export const { incremented, decremented } = counterSlice.actions
  16. const store = configureStore({
  17. reducer: counterSlice.reducer
  18. })
  19. store.subscribe(() => console.log(store.getState()))
  20. store.dispatch(incremented())
  21. store.dispatch(incremented())
  22. store.dispatch(decremented())

3. Redux 的学习资源

「@浪里淘沙的小法师」