React中使用@reduxjs/toolkit和react-redux进行状态管理

React中使用@reduxjs/toolkit和react-redux进行状态管理

1、安装依赖:
确保你的项目中已经安装了@reduxjs/toolkit和react-redux。可以使用以下命令进行安装:

npm install @reduxjs/toolkit react-redux

2、创建一个Slice模块来定义状态的初始值、actions和reducer。

// src/features/counterSlice.js

import {
    
     createSlice } from '@reduxjs/toolkit';

// 创建Slice
const counterSlice = createSlice({
    
    
  name: 'counter',
  initialState: {
    
    
     number:0,
     text:'你好'
  }, 
  reducers: {
    
     //同步修改state
    addnumber: (state,action) => {
    
    
        state.number=state.number+action.payload
    },
    decrement: (state,action) => {
    
    
     state.text=action.payload
    },
  },
});

// 导出actions
export const {
    
     addnumber, decrement} = counterSlice.actions;

// 导出reducer
export default counterSlice.reducer;

3、创建RootReducer模块:
创建一个RootReducer模块来集中管理所有的reducer。

// src/reducers/index.js

import {
    
     combineReducers } from '@reduxjs/toolkit';
import counterReducer from '../features/counterSlice';

// 将多个reducer合并为一个RootReducer
const rootReducer = combineReducers({
    
    
  counter: counterReducer,
});

export default rootReducer;

4、创建Store模块:
创建一个Store模块来配置Redux的store。

// src/store/index.js

import {
    
     configureStore } from '@reduxjs/toolkit';
import rootReducer from '../reducers';

// 创建并导出store
const store = configureStore({
    
    
  reducer: rootReducer,
});

export default store;

5、在入口文件中使用Provider:
在应用的入口文件中使用Provider组件来提供store。

// src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import {
    
     Provider } from 'react-redux';
import store from './store';
import App from './App';

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

6、在组件中使用状态:
在需要使用状态的组件中,使用useSelector钩子函数获取状态值,使用useDispatch钩子函数获取dispatch函数。

import React from 'react';
import {
    
     useSelector, useDispatch } from 'react-redux';
import {
    
     increment, decrement } from '../features/counterSlice';

function Counter() {
    
    
  const count = useSelector((state) => state.counter); // 获取counter状态
  const dispatch = useDispatch();

  const handleIncrement = () => {
    
    
    dispatch(increment()); // 分发increment action
  };

  const handleDecrement = () => {
    
    
    dispatch(decrement()); // 分发decrement action
  };

  return (
    <div>
      <p>Count: {
    
    count}</p>
      <button onClick={
    
    handleIncrement}>Increment</button>
      <button onClick={
    
    handleDecrement}>Decrement</button>
    </div>
  );
}

实现异步操作

创建异步Thunk:
在Slice模块中,使用createAsyncThunk来定义一个异步的thunk函数,用于处理异步操作。

// src/features/counterSlice.js

import {
    
     createSlice, createAsyncThunk } from '@reduxjs/toolkit';

// 异步操作的处理函数
const fetchCount = async () => {
    
    
  // 模拟异步操作
  await new Promise((resolve) => setTimeout(resolve, 1000));
  return 10;
};

// 创建异步thunk
export const fetchCountAsync = createAsyncThunk('counter/fetchCount', fetchCount);

// 创建Slice
const counterSlice = createSlice({
    
    
  name: 'counter',
  initialState: {
    
    
    value: 0,
    loading: false,
  },
  reducers: {
    
    
    increment: (state) => {
    
    
      state.value += 1;
    },
    decrement: (state) => {
    
    
      state.value -= 1;
    },
  },
  extraReducers: (builder) => {
    
    
    builder
      .addCase(fetchCountAsync.pending, (state) => {
    
    
        state.loading = true;
      })
      .addCase(fetchCountAsync.fulfilled, (state, action) => {
    
    
        state.value = action.payload;
        state.loading = false;
      });
  },
});

// 导出actions
export const {
    
     increment, decrement } = counterSlice.actions;

// 导出reducer
export default counterSlice.reducer;

组件中使用异步操作:
在组件中使用useEffect和useDispatch来触发异步操作并处理结果。

import React, {
    
     useEffect } from 'react';
import {
    
     useSelector, useDispatch } from 'react-redux';
import {
    
     increment, decrement, fetchCountAsync } from '../features/counterSlice';

function Counter() {
    
    
  const count = useSelector((state) => state.counter.value);
  const loading = useSelector((state) => state.counter.loading);
  const dispatch = useDispatch();

  useEffect(() => {
    
    
    dispatch(fetchCountAsync());
  }, [dispatch]);

  return (
    <div>
      <p>Count: {
    
    count}</p>
      {
    
    loading ? <p>Loading...</p> : null}
      <button onClick={
    
    () => dispatch(increment())}>Increment</button>
      <button onClick={
    
    () => dispatch(decrement())}>Decrement</button>
    </div>
  );
}

我们使用useEffect钩子函数在组件挂载后触发异步操作,通过dispatch(fetchCountAsync())来分发异步thunk函数。同时,通过loading状态来展示异步操作的加载状态。

猜你喜欢

转载自blog.csdn.net/NIKKT/article/details/131662708
今日推荐