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

0 コメント