前提
数字のカウンターを作成してReduxを学習しています。
下記はサンプルです。
サンプルのコードは、下記の動画を参考にして制作しました。
【React Redux】React Redux入門編!20分弱の動画で、React Reduxが学べる!?日本語で詳しく解説!(YouTube)
問題点
countの初期値0を所得出来ず、現状は下図の通り「count: 」と表示されます。
console.log(count)で確認したところ、undefinedでした。
実現したいこと
初期値である0を取得して、「count: 0」と表示させたいです。
使用しているライブラリ
- Redux
- React-Redux
TypeScriptも使用しています。
ソースコード
index.tsx
tsx
1import * as React from "react"; 2import { render } from "react-dom"; 3import { createStore } from "redux"; 4import { Provider } from "react-redux"; 5import counter from "./reducers/counter"; 6 7import App from "./App"; 8 9let store = createStore(counter); 10 11const rootElement = document.getElementById("root"); 12render( 13 <Provider store={store}> 14 <App /> 15 </Provider>, 16 rootElement 17);
App.tsx
tsx
1import * as React from "react"; 2import { increment, decrement } from "./actions/counter"; 3import { useSelector, useDispatch } from "react-redux"; 4 5export default function App() { 6 const count = useSelector((state: { count: number }) => state.count); 7 const dispatch = useDispatch(); 8 9 return ( 10 <> 11 <h1>count: {count}</h1> 12 <button onClick={() => dispatch(increment())}>+</button> 13 <button onClick={() => dispatch(decrement())}>-</button> 14 </> 15 ); 16}
reducers/counter.ts
typescript
1const counter = (count = 0, action: { type: string }) => { 2 switch (action.type) { 3 case "INCREMENT": 4 return count + 1; 5 case "DECREMENT": 6 return count - 1; 7 default: 8 return count; 9 } 10}; 11 12export default counter;
actions/counter.ts
TypeScript
1export const increment = () => { 2 return { 3 type: "INCREMENT" 4 }; 5}; 6 7export const decrement = () => { 8 return { 9 type: "DECREMENT" 10 }; 11};
現状のコードに対する認識レベルや私なりに推測した原因
- reducer/counter.tsの
const counter = (count = 0, action: { type: string }) => {
count = 0で初期値を設定できている
- countがundefinedになっているので、初期値ではなくcountそのものが取得できていない?
- reducerを見るにactionをdispatchすることでcountが返ってくるので、actionをdispatchするまではcountは存在しない?
試したこと
サンプルを作成するにあたり参考にした動画の通り、combineReducers
を経由させることで初期値を取得することができました。
reducers/reducers.ts
TypeScript
1import { combineReducers } from "redux"; 2import counter from "./counter"; 3 4const reducers = combineReducers({ 5 count: counter 6}); 7 8export default reducers;
しかし現状reducer
は1つなのと、combineReducers
を経由させるとなぜ初期値が取得できるか理解できていないので、combineReducers
を使用しない場合の実装方法をご教示いただきたいです。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。