安裝依賴
file:[安裝依賴包]
pnpm i @reduxjs/toolkit react-redux
實現計數器
createSlice
建立需要的變數和邏輯。
file:[src/store/counter-store.js]
import { createSlice } from "@reduxjs/toolkit";
const counterStore = createSlice({
name: "counterStore",
initialState: {
count: 0,
},
reducers: {
increament(state) {
state.count++;
},
decreament(state) {
state.count--;
},
},
});
const { increament, decreament } = counterStore.actions;
const counterReducer = counterStore.reducer;
export { increament, decreament, counterReducer };
配置 store。
file:[src/store/index.js]
import { configureStore } from "@reduxjs/toolkit";
import { counterReducer } from "./counter-store";
const store = configureStore({
reducer: {
counterReducer,
},
});
export default store;
注入 store。
file:[src/index.js]
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
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>
);
reportWebVitals();
useSelector
獲取 reducer,解構得到 count;透過 useDispatch
進行操作。
file:[src/App.js]
import "./App.css";
import { useSelector, useDispatch } from "react-redux";
import { decreament, increament } from "./store/counter-store";
function App() {
const { count } = useSelector((state) => state.counterReducer);
const dispatch = useDispatch();
return (
<div className="App">
<button onClick={() => dispatch(decreament())}>-</button>
{count}
<button onClick={() => dispatch(increament())}>+</button>
</div>
);
}
export default App;