react-redux-toolkit學習


react-redux負責狀態管理,使用toolkit插件可以更方便,具體使用方式簡單總結一下。
toolkit官網

安裝redux

使用toolkit的需要配置react-redux一起使用。

npm install react-redux@latest
npm install @reduxjs/toolkit

使用toolkit的步驟

  1. 配置一個reduxStore
import { configureStore } from '@reduxjs/toolkit';
export const store = configureStore({
    reducer: {},
});
  1. 把store發布到react項目中
import { Provider } from 'react-redux';
import { store } from './app/store';
import App from './App';

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root')
);
  1. 創建不定量的 redux state slice
    創建不同的slice.js
import { createSlice } from '@reduxjs/toolkit';

const initialState = {
    value: 0,
};

export const counterSlice = createSlice({
    name: 'counter',
    initialState,
    reducers: {
        increment: (state) => {
            state.value += 1;
        },
        decrement: (state) => {
            state.value -= 1;
        },
        incrementByAmount: (state, action) => {
            state.value += action.payload;
        },
    },
});
//Action creators are generated for each case reducer function
export const { increment, decrement, incrementByAmount } = counterSlice.actions
export default counterSlice.reducer
  1. 把 slice reducers 添加到 store 中
    next, we need add slice to our store. By defining a field inside the reducer parameter, we tell the store to use this slice reducer function to handle all updates to that state.
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counter/counterSlice'
export const store = configureStore({
    reducer: {
        counter: counterReducer,
    },
});
  1. 在組件中使用state和actions
import React from 'react';
import {useSelector, useDispatch} from 'react-redux';
import {increment, decrement} from './counterSlice';

export function Counter() {
    //從store中選擇所需要的對應的 state
    const count = useSelector((state) => state.counter.value);
    const dispatch = useDispatch();

    return (
        <div>
            <div>
                <button 
                    aria-label="Increment value"
                    onClick={() => dispatch(increment())}
                >
                    Increment
                </button>
                <span>{count}</span>
                <button 
                    aria-label="Decrement value"
                    onClick={() => dispatch(decrement())}
                >
                    Decrement
                </button>
            </div>
        </div>
    );
}

總結:

  1. 使用 toolkit 配置一個空狀態管理倉庫: store
  2. 將剛配置的空的狀態管理倉庫配合 react-redux中的 Provider 使用到項目中,一般需要將 Provider 包裹在項目的最頂層父級元素外,這樣可以保證這個store能夠存儲項目內的所有state.
  3. 使用toolkit中createSlice創建每個state對應的actions(一般一個狀態的reducer放置在一個單獨的文件中,便於管理和查看)
  4. 把第3步創建好的不定量個數的reducer配置到第1步創建的store中。
  5. 在項目中使用react-redux中提供的useSelectoruseDispatch分別負責從store中獲取對應的state以及觸發改變state的動作函數reducer.

注意:若state的動作函數是一個異步請求,則第3步中需要使用createAsyncThunk來創建state對應的action:

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

// First, create the thunk
const fetchUserById = createAsyncThunk(
  'users/fetchByIdStatus',
  async (userId, thunkAPI) => {
    const response = await userAPI.fetchById(userId)
    return response.data
  }
)

// Then, handle actions in your reducers:
const usersSlice = createSlice({
  name: 'users',
  initialState: { entities: [], loading: 'idle' },
  reducers: {
    // standard reducer logic, with auto-generated action types per reducer
  },
  extraReducers: (builder) => {
    // Add reducers for additional action types here, and handle loading state as needed
    builder.addCase(fetchUserById.fulfilled, (state, action) => {
      // Add user to the state array
      state.entities.push(action.payload)
    })
  },
})

// Later, dispatch the thunk as needed in the app
dispatch(fetchUserById(123))


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM