user-silce.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { createSlice } from '@reduxjs/toolkit';
  2. const userSlice = createSlice({
  3. name: 'user', // 指定状态片段的名称,类似与id的功能
  4. initialState: {
  5. name: '郭郭',
  6. age: 18,
  7. }, // 指定初始状态,就是默认状态
  8. reducers: {
  9. /**
  10. * 每一个reducer函数 都会接收 两个 参数
  11. * a: state 表示 当前状态
  12. * b: action 一个对象,表示一个修改状态的动作 {type: '', payload }
  13. */
  14. setName(state, action) {
  15. //! 在slice下所有的reducer函数中 可以直接修改状态,并且会保持响应式
  16. state.name = '小爱';
  17. },
  18. setAge(state, { payload }) {
  19. // console.log(`output->action`, action);
  20. state.age = payload;
  21. },
  22. }, // 用来定义修改状态的各种reducer函数
  23. });
  24. export default userSlice.reducer;
  25. // 在 slice对象中 会有一个属性 actions ,类型为对象。存储所有reducer函数对应构建action对象的函数
  26. // Action Creator
  27. export const { setName, setAge } = userSlice.actions;
  28. // 异步处理,需要定义thunk函数
  29. // export function asyncSetAge(age) {
  30. // return (dispatch, getState) => {
  31. // setTimeout(() => {
  32. // dispatch(setAge(Number(age) || 0));
  33. // }, 1000);
  34. // };
  35. // }
  36. // 上面代码优化
  37. export const asyncSetAge = (age) => (dispatch, getState) => {
  38. setTimeout(() => {
  39. dispatch(setAge(Number(age) || 0));
  40. }, 1000);
  41. };
  42. // export const asyncSetAge = (dispatch, getState) => {
  43. // // console.log(dispatch);
  44. // // console.log(getState);
  45. // // let state = getState();
  46. // // console.log(state);
  47. // setTimeout(() => {
  48. // dispatch(setAge(Number(age) || 0));
  49. // }, 1000);
  50. // };