[React] Detailed explanation of Redux Toolkit usage

1. Install Redux Toolkit and React-Redux

注: “@reduxjs/toolkit”: “^1.8.6”, “react-redux”: “^8.0.4”

npm install @reduxjs/toolkit react-redux

2. Create a Redux Store

Importing configureStore from Redux Toolkit, we'll start by creating and exporting an empty Redux store.

store/index.js
// 使用rtk来创建store
import {
    
     configureStore } from '@reduxjs/toolkit'
import useReducer from './userSlice'

/* 
使用rtk的时候,reducer依然可以使用之前的创建不变
但是不再需要去合并reducer combineReducers
rtk提供了configureStore方法,直接接收一个对象作为参数
可以将reducer的相关配置直接通过这个对象进行传递,不再需单独合并reducer
reducer属性可以直接单独传递一个ruducer,也可以传递一个对象

*/

const store = configureStore({
    
    
  reducer: {
    
    
    user: useReducer
  }
})

export default store

3. Using Redux Store in React

We can wrap our application with React-Redux in the src/index.js file, so that we can use the React store in the React component

The specific operation is to first introduce the Redux store we just created, then wrap yours with it, and then pass in the store as a prop.
src/index.js

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

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

4. Create a Redux State Slice

A slice requires a name as a unique identifier, an initial state value, and at least one reducer method to define how the state changes. Once the slice is created we can export the generated Redux action creators and reducer methods for the entire slice.

Redux requires us to immutably update state by making copies of data and updating copies. However, Redux Toolkit's createSlice and createReducer APIs use Immer internally, which allows us to write the update logic directly without having to make a copy, and it will automatically become a correct immutable update.

userSlice.js file

// 切片对象
import {
    
     createSlice } from '@reduxjs/toolkit'
/* 
reducer切片
createSlice函数的作用:生成分片的reducer
内部调用的市createAction和createReducer 
creatSlice可以帮助我们用更少的代码去生成配套的reducer和action,而且有很好的维护性
*/


const userSlice = createSlice({
    
    
  name: 'zhangsan', // 标识符,生成actions的时候要使用,
  // state初始值
  initialState: {
    
    
    name: '张三',
    age: 18,
    gender: '男'
  } ,
  // reducer的具体方法,
  reducers: {
    
    
    // 指定state的各种操作,直接就可以在对象中添加方法
    setName(state, action) {
    
    
      /* 
      可以通过不同的方法修来指定对state的不同的操作
      state,action 
      可以直接修改state => state 是一个代理对象  之前的复制一份,返回一个新的对象
      */
      state.name = action.payload
    },
    setAge(state, action) {
    
    
      state.age = action.payload
    }
  }
})
/* 
切片对象会自动地帮助我们生成action
切片对象会根据我们地reducers方法来自动地创建action对象,这些action对象会保存到切片对象的actions中

{type:name/函数名,payload:函数的参数}

*/

// 实际开发中,setName,setAge对外暴露,
export const {
    
     setName, setAge } = userSlice.actions
export default userSlice.reducer

5. Use Redux State and Action in React components

Now we can manipulate the Redux store in React components using React-Redux hooks. We can use useSelector to read data from the store, or use useDispatch to dispatch actions.

src/App.js

import React from 'react'
import {
    
     useSelector, useDispatch } from 'react-redux'
import {
    
     setName, setAge } from './store/userSlice'

export default function App() {
    
    
  const user = useSelector(state => state.user)
  const dispatch = useDispatch()

  const setNameHandler = () => {
    
    
    dispatch(setName('李四'))
  }

  const setAgeHandler = () => {
    
    
    dispatch(setAge(20))
  }

  return (
    <div>
      <h1>{
    
    user.name}</h1>
      <h1>{
    
    user.age}</h1>
      <h1>{
    
    user.gender}</h1>
      <button onClick={
    
    setNameHandler}>修改name</button>
      <button onClick={
    
    setAgeHandler}>修改年龄</button>
    </div>
  )
}

The above is a brief overview on how to setup and use Redux Toolkit in React. Review details:

1. Use configureStore to create a Redux Store

  • configureStore receives the reducer method as a named parameter, or as an attribute of the reducer object

  • configureStore will automatically set up the store with the default settings

2. Use Redux store in React components

  • Wrap your with React-Redux provided
  • Use incoming Redux store

3. Create a Redux "slice" reducer using createSlice

  • createSlice needs to have a name attribute as a unique identifier, and also needs to initialize the state and the named reducer method
  • The Reducer method can directly "change" the state by using Immer without having to manually make a copy
  • Export the generated slice reducer and action creators

4. Use React-Redux's useSelector/useDispatch hooks in React components

  • Use the useSelector hook to read data from the store
  • Use the useDispatch hook to get the dispatch method, and dispatch actions as needed

Guess you like

Origin blog.csdn.net/weixin_50636536/article/details/128357155