reducer.js 918 B

1234567891011121314151617181920212223242526272829
  1. import { createSlice } from '@reduxjs/toolkit';
  2. export const counterSlice = createSlice({
  3. name: 'counter',
  4. // 状态
  5. initialState: {
  6. value: 0,
  7. },
  8. // 修改的方法
  9. reducers: {
  10. increment: (state) => {
  11. // Redux Toolkit 允许我们在 reducers 中编写 mutating 逻辑。
  12. // 它实际上并没有 mutate state 因为它使用了 Immer 库,
  13. // 它检测到草稿 state 的变化并产生一个全新的基于这些更改的不可变 state
  14. state.value += 1;
  15. },
  16. decrement: (state) => {
  17. state.value -= 1;
  18. },
  19. incrementByAmount: (state, action) => {
  20. state.value += action.payload;
  21. },
  22. },
  23. });
  24. // 为每个 case reducer 函数生成 Action creators
  25. export const { increment, decrement, incrementByAmount } = counterSlice.actions;
  26. export default counterSlice.reducer;