こちらのプログラムを改造しました。
Next.js: Redux Toolkit の使い方 (Typescript)
プロジェクトの作成
npx create-next-app ex03 --ts
cd ex03
yarn add @reduxjs/toolkit react-redux
yarn dev
プログラム
pages/index.tsx
// ---------------------------------------------------------------
// index.tsx
//
// ---------------------------------------------------------------
import { useDispatch, useSelector } from "react-redux";
import { counterSlice, CounterState, store } from "./_app";
import { NextPage } from "next";
// ---------------------------------------------------------------
const Home: NextPage = () => {
const dispatch = useDispatch();
const selector = useSelector((state: CounterState) => state);
const { khm012,khm015,khm024,khm027,khm050,khm053 } = counterSlice.actions;
return (
<div>
<h1>[グリムの昔話]</h1>
<button onClick={() => { dispatch(khm012()); }} > KHM012 </button>
<button onClick={() => { dispatch(khm015()); }} > KHM015 </button>
<button onClick={() => { dispatch(khm024()); }} > KHM024 </button>
<button onClick={() => { dispatch(khm027()); }} > KHM027 </button>
<button onClick={() => { dispatch(khm050()); }} > KHM050 </button>
<button onClick={() => { dispatch(khm053()); }} > KHM053 </button>
<p>{store.getState().counter.value}</p>
<p>Jun/27/2022 PM 14:55</p>
</div>
);
};
export default Home;
// ---------------------------------------------------------------
_app.tsx
// ---------------------------------------------------------------
// _app.tsx
//
// ---------------------------------------------------------------
import React from "react";
import type { AppProps } from "next/app";
import { Provider } from "react-redux";
import { configureStore, createSlice } from "@reduxjs/toolkit";
// ---------------------------------------------------------------
export type CounterState = {
value: string;
};
// ---------------------------------------------------------------
const initialState: CounterState = { value: "" };
// ---------------------------------------------------------------
export const counterSlice = createSlice({
name: "counter",
initialState,
reducers: {
khm012(state) { state.value = "ラプンツェル"; },
khm015(state) { state.value = "ヘンゼルとグレーテル"; },
khm024(state) { state.value = "ホレおばさん"; },
khm027(state) { state.value = "ブレーメンの音楽隊"; },
khm050(state) { state.value = "いばらひめ"; },
khm053(state) { state.value = "白雪ひめ"; },
},
});
// ---------------------------------------------------------------
export const store = configureStore({
reducer: {
counter: counterSlice.reducer,
},
});
// ---------------------------------------------------------------
function MyApp({ Component, pageProps }: AppProps) {
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
);
}
export default MyApp;
// ---------------------------------------------------------------
ブラウザーで、 http://localhost:3000/ にアクセス