createSlice

废话少说,直接上代码

export const initialState: pageState = {
  dataList: [{
    age: 12,
    name: 'wasdfga',
    sex: 'man',
  }],
  flag: false,
};
const slice = createSlice({
  name: NAMESPACE,
  initialState,
  reducers: {
    updateItem(state, action: PayloadAction<number>) {
      state.dataList[action.payload].age += 1;
    },
    updateFlag(state) {
      state.flag = !state.flag;
    },
  },
});

export const { actions, reducer } = slice;
console.log(slice);

打印出来的值如下:
可以看出这个方法用来生成actions(都是同步操作)和reducers。
在@reduxjs/toolkit有单独分别生成actions和reducers的方法,其实createSlice方法内部就是使用了createAction、createReducer。
在这里插入图片描述

createAsyncThunk

那么对于一些异步请求的action怎么办呢?就是createAsyncThunk了

export const testApi = createAsyncThunk(
  `${NAMESPACE}/testApi`,
  //发出一个请求,这里用的是axios
  async (params) => await services.testApi(params),
)
const slice = createSlice({
  name: NAMESPACE,
  initialState,
  reducers: {
    ...
  },
  // 处理异步请求结果的reducer
  extraReducers: (builder) => {
    builder.addCase(testApi.fulfilled, (state, action) => {
      const data = action.payload && action.payload.data; // data为接口返回的data字段
      console.log(data);
    })
  },
});
export const { actions, reducer } = slice;
//testApi.fulfilled中的fulfilled还可以是padding和rejected两种结果

在UI组件中使用


import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { actions, testApi } from '../redux/slice';
import { IListItem, pageState } from '../interface/types';
const { useEffect } = React;
require('../style/index');

function IndexPage(props) {
  // 使用dispatch触发action
  const dispatch = useDispatch();
  // 这里获取state中响应式数据
  const { dataList, flag } = useSelector(
    (state: pageState) => state,
  );

  const getData = () => {
    dispatch(testApi());
  }
  const itemClickhandle = (item: IListItem, index: number) => {
    dispatch(actions.updateItem(index));
    dispatch(actions.updateFlag());
  }

  getData();
  return (
    <div className='test-page-container'>
      {dataList.map((item, index) => (
        <p
          className='list-item'
          key={item.age}
          onClick={() => itemClickhandle(item, index)}
        >
          {`name is ${item.name}---age is ${item.age} &&& flag is ${flag}`}
        </p>)
      )}
    </div>
  );
}

export default IndexPage;

最后附上代码仓库地址 my-react/src/pages/test目录下

git clone https://github.com/maguofu/my-react.git
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐