請用十歲孩童也能懂的方法,講解 react.js redux 使用方法跟原理給我聽?

1 min read
讓我用一個有趣的比喻來解釋 Redux!
🎮 想像一個遊戲機中心
1. 遊戲機中心(Store)
這是一個大房間,裡面放著所有的遊戲分數
只有一個管理員在管理所有分數
2. 遊戲規則(Reducer)
// 遊戲規則範例
const gameReducer = (state = { score: 0 }, action) => {
switch (action.type) {
case '加分':
return { score: state.score + 10 };
case '扣分':
return { score: state.score - 5 };
default:
return state;
}
}
3. 遊戲指令卡(Action)
- 就像遊戲卡片一樣,上面寫著你要做什麼
// 加分卡
const addScore = {
type: '加分'
}
// 扣分卡
const minusScore = {
type: '扣分'
}
4. 送出指令(Dispatch)
// 當你打中目標,送出加分卡
store.dispatch(addScore);
🎮 實際使用範例
// 1. 創建遊戲機中心
import { createStore } from 'redux';
const store = createStore(gameReducer);
// 2. 聽取分數變化
store.subscribe(() => {
console.log('目前分數:', store.getState().score);
});
// 3. 玩遊戲(發送指令)
store.dispatch(addScore); // 分數 +10
store.dispatch(addScore); // 分數 +10
store.dispatch(minusScore); // 分數 -5
🌟 重點整理:
所有分數都放在一個地方(Store)
想要改變分數要用指令卡(Action)
管理員依照規則改分數(Reducer)
只能用指令卡改分數(Dispatch)
這樣想像是不是比較容易懂啦?就像玩遊戲一樣!
0
Subscribe to my newsletter
Read articles from Sun Pochin directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Sun Pochin
Sun Pochin
I was the main web front-end engineer responsible for developing and maintaining the customer-facing platform for WisdomHall (品學堂) in 2024 Q3 Q4, code reviewed by CTO and a senior engineer. http://learning.wisdomhall.com.tw has total active 257k users, according to their Facebook post: https://www.facebook.com/share/p/1MnjbwZxCV/ My tech stack includes JavaScript, Vue 2, Nuxt 2, git, and Docker.