react经验3:状态管理组件redux的简单应用

针对最新版的react@18版本编写,使用函数式组件

步骤1:安装依赖

npm install @reduxjs/toolkit react-redux

步骤2:声明slice

案例命名为/src/store/userSlice.ts

import { createSlice, PayloadAction } from '@reduxjs/toolkit';
//声明状态类型
export declare type UserState = {
    name: string;
    code: string;
}
//初始化状态值
const initialState: UserState = {
    name: '',
    code: ''
}
//声明slice
const userSlice = createSlice({
    name: 'user',
    initialState,
    reducers: {
    	//声明可以操作state的方法
        setUserInfo: (state, action: PayloadAction<UserState>) => {
            state.name = action.payload.name;
            state.code = action.payload.code;
        }
    }
});
//导出声明的state方法
export const { setUserInfo } = userSlice.actions;
//导出slice
export default userSlice;

步骤3:声明store

本案例命名为/src/store/index.ts

import { configureStore } from "@reduxjs/toolkit";
import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux";
import userSlice from "./userSlice";
//声明store,绑定上一步创建的slice
const store = configureStore({
    reducer: {
        user: userSlice.reducer
    }
});
//导出store
export default store;

// 从 store 本身推断出 `RootState` 和 `AppDispatch` 类型
type RootState = ReturnType<typeof store.getState>;
type AppDispatch = typeof store.dispatch;

//导出的这俩hook,一个用于操作步骤2声明的reducer的方法,一个用于取state的值
export const useAppDispatch: () => AppDispatch = useDispatch;
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

应用state

首先在index.tsx中,使用provider注入store

import store from './store';
import { Provider } from 'react-redux';
root.render(
  <Provider store={store}>
    <App/>
  </Provider>
);

然后在需要使用的页面中

import { useAppDispatch, useAppSelector } from "../store";
import { setUserInfo } from "../store/userSlice";
const userInfo = useAppSelector(state => state.user);
const dispatch = useAppDispatch();

使用state

<label>{userInfo.name}({userInfo.code})label>

改变state

dispatch(setUserInfo({
	code: '001',
	name: '啊大苏打'
}));

你可能感兴趣的:(web前端,react.js,javascript,前端)