React 之 react-redux redux-toolkit

发布时间:2023年12月28日

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>
    )
}
文章来源:https://blog.csdn.net/zhenshu_guo/article/details/135158160
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。