官网: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
yarn add @reduxjs/toolkit
安装 Redux
yarn add redux
2. 两个例子
一个简单的 Redux 例子
import { createStore } from 'redux'
function counterReducer(state = { value: 0 }, action) {
switch (action.type) {
case 'counter/incremented':
return { value: state.value + 1 }
case 'counter/decremented':
return { value: state.value - 1 }
default:
return state
}
}
let store = createStore(counterReducer)
store.subscribe(() => console.log(store.getState()))
store.dispatch({ type: 'counter/incremented' })
store.dispatch({ type: 'counter/incremented' })
store.dispatch({ type: 'counter/decremented' })
一个使用 Redux Toolkit 的例子
const counterSlice = createSlice({
name: 'counter',
initialState: {
value: 0
},
reducers: {
incremented: state => {
state.value += 1
},
decremented: state => {
state.value -= 1
}
}
})
export const { incremented, decremented } = counterSlice.actions
const store = configureStore({
reducer: counterSlice.reducer
})
store.subscribe(() => console.log(store.getState()))
store.dispatch(incremented())
store.dispatch(incremented())
store.dispatch(decremented())
3. Redux 的学习资源
- Redux 核心教学:https://redux.js.org/tutorials/essentials/part-1-overview-concepts
- Redux 原理教学:https://redux.js.org/tutorials/fundamentals/part-1-overview
- Redux 视频教学:https://www.learnwithjason.dev/let-s-learn-modern-redux
「@浪里淘沙的小法师」