Redux Toolkit使用

1、引入

yarn add @reduxjs/toolkit react-redux
 or
npm install @reduxjs/toolkit react-redux

2、入口js文件引入store

import React from "react";
import ReactDOM from "react-dom";
import reportWebVitals from "./reportWebVitals";
import Router from "./router";
import { Provider } from "react-redux";
import store from "@store";

ReactDOM.render(
  <Provider store={store}>
    <Router />
  </Provider>,
  document.getElementById("root")
);

reportWebVitals();

3、创建store/index.js、store/features/userSlice.js

store/index.js

import { configureStore } from "@reduxjs/toolkit";
import userSlice from "./features/userSlice";
export default configureStore({
  reducer: {
    user: userSlice,
  },
});

store/features/userSlice.js

import { createSlice } from "@reduxjs/toolkit";
import { fetchContractAddress } from "@common/api";
export const userSlice = createSlice({
  name: "user", // 命名空间,在调用action的时候会默认的设置为action的前缀
  // 初始值
  initialState: {
    data: [],
  },
  // 这里的属性会自动的导出为actions,在组件中可以直接通过dispatch进行触发
  reducers: {
    getData(state, { payload }) {
      console.log(333333333, state.data, payload);
      state.data = payload;
    },
  },
});
// 导出actions
export const {getData } = userSlice.actions;

// 内置了thunk插件,可以直接处理异步请求
export const fetchContract = (payload) => async (dispatch) => {
  console.log(123, payload, dispatch);
  const result = await fetchContractAddress(); //接口请求
  if (result) {
    dispatch(getData(result));
  }
};

export default userSlice.reducer; // 导出reducer,在创建store时使用到

4、在项目中使用

import { useEffect } from "react";
import { fetchContract } from "@store/features/userSlice";
import { useSelector, useDispatch } from "react-redux";

const Test = () => {
  const { data } = useSelector((state) => state.user);
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(fetchContract("test"));
  }, []);
  console.log("data", data);
  return <div>test</div>;
};

export default Test;

你可能感兴趣的:(react.js,js)