记 react-redux redux-toolkit

发布时间 2023-12-09 16:13:42作者: 还是一直这样

1、安装

npm install @reduxjs/toolkit react-redux

2、使用

2.1 创建一个 Redux Store

app/store.js

import { configureStore } from '@reduxjs/toolkit'

export const store = configureStore({
  reducer: {},
})

2.2 提供 Redux Store 来 React

index.js

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

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

2.3 创建 Redux State Slice

features/counter/counterSlice.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
        }
    }
})


export const { increment, decrement, incrementByAmount } = counterSlice.actions

export default counterSlice.reducer

2.4 将 Slice Reducers 添加到 store

app/store.js

import { configureStore } from '@reduxjs/toolkit'
import counterReducer from './features/counter/counterSlice'


export const store = configureStore({
    reducer: {
        counter: counterReducer,
    },
})

2.5 在 React 组件中使用 Redux State 和 Actions

features/counter/Counter.js

import React from "react"
import { useSelector, useDispatch } from "react-redux"
import { decrement, increment, incrementByAmount } from "./counterSlice"


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

    return (
        <div>
            <button onClick={() => { dispatch(decrement()) }}>减</button>

            <span>{count}</span>

            <button onClick={() => { dispatch(increment()) }}> 加</button>

            <button onClick={() => { dispatch(incrementByAmount(2)) }}> 加 2</button>
        </div>
    )
}