Using @reduxjs/toolkit and react-redux for state management in React

Using @reduxjs/toolkit and react-redux for state management in React

1. Install dependencies:
Make sure @reduxjs/toolkit and react-redux are installed in your project. It can be installed using the following command:

npm install @reduxjs/toolkit react-redux

2. Create a Slice module to define the initial value of the state, actions, and 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. Create RootReducer module:
Create a RootReducer module to centrally manage all reducers.

// 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. Create a Store module:
Create a Store module to configure the 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. Use Provider in the entry file:
Use the Provider component in the application's entry file to provide the 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. Use status in components:
In components that need to use status, use the useSelector hook function to obtain the status value, and use the useDispatch hook function to obtain the dispatch function.

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>
  );
}

Implement asynchronous operations

Create an asynchronous Thunk:
In the Slice module, use createAsyncThunk to define an asynchronous thunk function for processing asynchronous operations.

// 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;

Use asynchronous operations in components:
Use useEffect and useDispatch in components to trigger asynchronous operations and process the results.

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>
  );
}

We use the useEffect hook function to trigger asynchronous operations after the component is mounted, and dispatch the asynchronous thunk function through dispatch(fetchCountAsync()). At the same time, the loading status of asynchronous operations is displayed through the loading status.

Guess you like

Origin blog.csdn.net/NIKKT/article/details/131662708
Recommended