Skip to content

Redux Toolkit

什么是 Redux Toolkit

Redux Toolkit 是一个官方的 Redux 标准工具包,它可以帮助你编写 Redux 逻辑更少、更简单。它包含了一些有用的函数和工具,可以帮助你编写 Redux 代码更少,更简洁。

安装

bash
npm install @reduxjs/toolkit react-redux

使用

ts
import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./slice";

export const store = configureStore({
    reducer: {
        counter: counterReducer,
    },
});
ts
import { createSlice } from "@reduxjs/toolkit";

export const counterSlice = createSlice({
    name: "counter",
    initialState: {
        value: 0,
    },
    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;
tsx
import { useDispatch, useSelector } from "react-redux";
import { decrement, increment, incrementByAmount } from "./slice";

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

    return (
        <div>
            <h2>Counter: {count}</h2>
            <div>
                <button
                    aria-label="Increment value"
                    onClick={() => dispatch(increment())}
                >
                    Increment
                </button>
                <button
                    aria-label="Decrement value"
                    onClick={() => dispatch(decrement())}
                >
                    Decrement
                </button>
                <button
                    aria-label="Increment by 10"
                    onClick={() => dispatch(incrementByAmount(10))}
                >
                    Increment by 10
                </button>
            </div>
        </div>
    );
}
tsx
import { Provider } from "react-redux";
import { store } from "./store";
import Counter from "./Counter";

export default function ReduxDemo() {
    return (
        <Provider store={store}>
            <Counter />
        </Provider>
    );
}