React Redux 8.0.5 使用

时间:2023-01-28 浏览:160 分类:React

React Redux 是 Redux 的官方 React UI 绑定层。它允许 React 组件从 Redux 存储中读取数据,并将操作分派到存储以更新状态。

使用方法

第一步:安装依赖

$ npm install react-redux

第二步:定义Reducers

import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import type { RootState } from "../store";

// Define a type for the slice state
interface CounterState {
  value: number;
}

// Define the initial state using that type
const initialState: CounterState = {
  value: 0,
};

export const counterSlice = createSlice({
  name: "counter",
  // `createSlice` will infer the state type from the `initialState` argument
  initialState,
  reducers: {
    increment: (state) => {
      state.value += 1;
    },
    decrement: (state) => {
      state.value -= 1;
    },
    // Use the PayloadAction type to declare the contents of `action.payload`
    incrementByAmount: (state, action: PayloadAction<number>) => {
      state.value += action.payload;
    },
  },
  extraReducers(builder) {
    builder.addCase("RESET", (state, action) => {
      state.value = 100;
    });
  },
});

export const { increment, decrement, incrementByAmount } = counterSlice.actions;

// Other code such as selectors can use the imported `RootState` type
export const selectCount = (state: RootState) => state.users.value;

export const usersReducer = counterSlice.reducer;

其中定义了三个方法 increment, decrement, he incrementByAmount, 后面的extraReducers为自定义 方法,这里将action.type 名称定义为 RESET。在组建中这两类的调用也不一样,后面演示。

第三步:创建Store

import { configureStore } from "@reduxjs/toolkit";
import { usersReducer } from "./reducers/user.reducer";

const store = configureStore({
  reducer: {
    users: usersReducer,
  },
});

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch;

export default store;

第四步:在根组件引入Store

const root = ReactDOM.createRoot(
  document.getElementById("root") as HTMLElement
);
root.render(
  <Provider store={store}>
    <App />
  </Provider>
);

第五步:组件内调用方法操作元数据

 _类组件

import { Component } from "react";
import { connect } from "react-redux";
import { Dispatch } from "redux";
import { RootState } from "../store/store";
import {
  increment,
  decrement,
  incrementByAmount,
} from "../store/reducers/user.reducer";

interface Iuser {
  users: { value: number };
  increment: () => void;
  decrement: () => void;
  incrementByAmount: (amount: number) => void;
  reset: () => void;
}

class User extends Component<Iuser> {
  constructor(props: Iuser) {
    super(props);

    this.state = {
      count: 0,
    };
  }

  render() {
    return (
      <>
        <h1>Users</h1>
        <p>Users: {this.props.users.value}</p>
        <button onClick={this.props.increment}>Increment</button>
        <button onClick={this.props.decrement}>Decrement</button>
        <button onClick={() => this.props.incrementByAmount(5)}>Add5</button>
        <button onClick={this.props.reset}>Reset</button>
      </>
    );
  }
}

const mapStateToProps = (state: RootState) => {
  return {
    users: state.users,
  };
};

const mapDispatchToProps = (dispatch: Dispatch) => {
  return {
    increment: () => {
      dispatch(increment());
    },
    decrement: () => {
      dispatch(decrement());
    },
    incrementByAmount: (amount: number) => {
      dispatch(incrementByAmount(amount));
    },
    reset: () => {
      dispatch({ type: "RESET" });
    },
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(User);

 

 _函数组件

首先定义hooks

import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'
import type { RootState, AppDispatch } from './store'

// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch: () => AppDispatch = useDispatch
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector

随后在函数组件中引入

import React from "react";
import { useAppSelector } from "../store/hooks";
import { selectCount } from "../store/reducers/user.reducer";
import { useAppDispatch } from "../store/hooks";
import {
  increment,
  decrement,
  incrementByAmount,
} from "../store/reducers/user.reducer";

const Admin: React.FC = () => {
  const users = useAppSelector((state) => state.users);   // 获取reducer的对象
  const count = useAppSelector(selectCount);   // 直接获取state元数据
  const dispatch = useAppDispatch();

  return (
    <div>
      <h1>Admin</h1>
      <p>Users: {users.value}</p>
      <p>Count: {count}</p>
      <button
        onClick={() => {
          dispatch(increment());
        }}
      >
        Increment
      </button>
      <button
        onClick={() => {
          dispatch(decrement());
        }}
      >
        Decrement
      </button>
      <button onClick={() => dispatch(incrementByAmount(5))}>Add5</button>
      <button
        onClick={() => {
          dispatch({ type: "RESET" });
        }}
      >
        Reset
      </button>
    </div>
  );
};

export default Admin;