Redux Toolkit 极简示例:Let’s buy some ice-cream! (Part 2)
2. 买点 IceCream 吧!
根据上一章的内容实现页面上 BuyIceCream
的功能。
2.1 创建 ice-cream 的 Slice
与 1.4.2 章类似,在 src/store/reducers/
文件夹下创建一个 icecream.js
文件用于处理 ice-cream 数量的记录和修改,并导出 Action Creaters 和 reducer。
这里,先暂时只创建 increment
这一 reducer,让购买按钮按下时增加冰激凌的数量。
// src/store/reducers/icecream.js
// 创建一个 icecream 的 slice,用于ice-cream数量的修改
import { createSlice } from "@reduxjs/toolkit";
export const icecreamSlice = createSlice({
name: "icecream",
initialState: {
value: 0
},
reducers: {
increment: (state) => {
state.value += 1;
},
},
})
export const { increment } = icecreamSlice.actions;
export default icecreamSlice.reducer;
2.2 将 ice-cream 的 Slice Reducer 添加到 Store 中
与 1.5章类似,引入上一节写好的 reducer,此时的 src/store/index.js
文件变成:
// src/store/index.js
import { configureStore } from "@reduxjs/toolkit";
import moneyReducer from "./reducers/money";
import icecreamReducer from "./reducers/icecream"; // 引入icecreamReducer
export default configureStore({
reducer: {
money: moneyReducer,
icecream: icecreamReducer, // 将icecreamReducer加入到store中
},
});
2.3 在 React 组件中使用 Redux 操作 ice-cream 的数量
与上一章处理 Money 的方法类似,需要在 App.js
中引入之前写好的 Action,然后使用 useSelector
获取 store 中 icecream
的值,并且在页面上将它正确的显示出来。最后在对应 <button>
的 onClick
属性传入正确的方法来更新它。
首先,引入对应的 Action:
// src/App.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './store/reducers/money';
import { increment as buyIcecream } from './store/reducers/icecream'; // 引入 increment action
// ...
和第一章不同的是,引入时使用了 increment as buyIcecream
的写法,将 icecream
的 increment
action 起了一个“别名”:buyIcecream
。这是因为 increment
这个名字已经被 money
的 Action 占用了。
因此,在后续的代码中,将使用 buyIcecream
这个别名来操作 icecream
的增加。
继续完成 App.js
的修改:
// src/App.js
// ...
import { increment as buyIcecream } from './store/reducers/icecream'; // 引入 increment action
const App = () => {
// ...
const icecream = useSelector((state) => state.icecream.value); // 从store中获取icecream的值
return (
{/* ... */}
{/* 在页面上显示icecream的值,并处理button的点击 */}
IceCream Count: {icecream}
<button onClick={() => dispatch(buyIcecream())}>Buy IceCream</button> <br />
{/* ... */}
)
}
// ...
此时在页面上点击 BuyIceCream
按钮就可以观察到冰激凌数量的变化了。
以上内容的完整代码在本项目的 ChapterTwo 分支。