javascript Redux中的combineReducer将状态嵌套在每个状态项中,我不知道为什么

ut6juiuv  于 2023-05-16  发布在  Java
关注(0)|答案(1)|浏览(90)

在React中使用Redux构建一个游戏,我在使用combineReducer时遇到了问题。当我向createStore传递一个reducer时,一切都很好,但当我尝试使用合并reducers时,我开始遇到问题
import React,{ useState,useEffect } from“react”; import { useSelector } from“react-redux”;

const Hero = () => {

  const heroPosX = useSelector((state) => state.heroPosX);
  const heroPosY = useSelector((state) => state.heroPosY);
  console.log(heroPosX, heroPosY);
  • 当我注销heroPosX和heroPosY时,我得到一个包含整个状态的对象。获取实际数据值的唯一方法是

const heroPosX = useSelector((state)=> state.heroPosX.heroPosX);
我的索引文件

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { Provider } from "react-redux"; //redux
import { combineReducers, createStore } from "redux"; 

import { keyStates } from "./redux/keyStates";
import { heroPosX, heroPosY } from "./redux/heroPosition";
//combines reducers, to enable use of multiple reducers
const rootReducer = combineReducers({

  heroPosX,
  heroPosY,
});

//redux boilerplate
const store = createStore(
  rootReducer,
  window._REDUX_DEVTOOLS_EXTENSION__ && window._REDUX_DEVTOOLS_EXTENSION__()
);
//redux devtools extension adds redux devtoools to the browser
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  //<Provider> </Provider> is part of redux
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: XXXXXXXXXXXXXX
reportWebVitals();

我的减速器

import { initialState } from "./initialState";

export function heroPosX(state = initialState, action) {
  switch (action.type) {
    case "MOVE_X":
      return { ...state, heroPosX: state.heroPosX + 10 };

    default:
      return state;
  }
}

export function heroPosY(state = initialState, action) {
  switch (action.type) {
    case "MOVE_Y":
      return { ...state, heroPosY: state.heroPosY + 10 };
    default:
      return state;
  }
}

有人能看出我错在哪里吗?
我尝试了各种解决方案,但似乎都不起作用。

wwwo4jvm

wwwo4jvm1#

import { initialState } from "./initialState";

export function heroPosX(state = initialState, action) {
  switch (action.type) {
    case "MOVE_X":
       state + 10 };

    default:
      return state;
  }
}

export function heroPosY(state = initialState, action) {
  switch (action.type) {
    case "MOVE_Y":
      return state + 10;
    default:
      return state;
  }
}

combineReducers已经创建了顶级密钥。reducer的作用域是相关的状态块。
另外,确保initialState不是一个对象,而只是一个值(可能是0?)

相关问题