現在Reduxを使い、state管理を行なっています。
とあるactionでstateを全て変更しようとした際にactionは走るのですが、state側に変更がかからず困っています。
下記に失敗例と成功例載せておきます。
自分なりに考えたのは、state全体を変更するのはobjectを渡しているので、参照渡しとして認識され変更がかからないのかな?と思っています。
Reduxを触って日が浅いので、ご教授お願いします。
失敗例
index.js
1import { createSlice } from "@reduxjs/toolkit"; 2import { areaState } from "../initialState/areaState"; 3 4const initialState = { 5 hoge: 1, 6 fuga: "テスト" 7 }, 8 9export const applicationModule = createSlice({ 10 // 一意の名前 11 name: "APP", 12 initialState, 13 // 操作の内容 14 reducers: { 15 set(state, action) { 16 state = action.payload; 17 }, 18 }, 19}); 20 21export const { set } = applicationModule.actions; 22
jsx
1import { useDispatch, useSelector } from "react-redux"; 2import { setAreaInfo } from "../../store/application"; 3import { areaState } from "../../store/initialState/areaState"; 4 5export const Test = () => { 6 const data = { 7 hoge: 2, 8 fuga: "本番" 9 } 10 const dispatch = useDispatch(); 11 const { hoge } = useSelector((state) => state.application); 12 const set = () => { 13 dispatch(set(data)); 14 }; 15 return ( 16<div> 17 <button onClick={set}></button> 18 <div>{hoge}</div> 19</div> 20 ); 21}; 22
成功例
js
1import { createSlice } from "@reduxjs/toolkit"; 2import { areaState } from "../initialState/areaState"; 3 4const initialState = { 5 hoge: 1, 6 fuga: "テスト" 7 }, 8 9export const applicationModule = createSlice({ 10 // 一意の名前 11 name: "APP", 12 initialState, 13 // 操作の内容 14 reducers: { 15 setHoge(state, action) { 16 state.hoge = action.payload; 17 }, 18 }, 19}); 20 21export const { setHoge } = applicationModule.actions; 22
jsx
1import { useDispatch, useSelector } from "react-redux"; 2import { setAreaInfo } from "../../store/application"; 3import { areaState } from "../../store/initialState/areaState"; 4 5export const Japan = () => { 6 const dispatch = useDispatch(); 7 const { hoge } = useSelector((state) => state.application); 8 const set = () => { 9 dispatch(setHoge(4)); 10 }; 11 return ( 12<div> 13 <button onClick={set}></button> 14 <div>{hoge}</div> 15</div> 16 ); 17}; 18

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。