【问题标题】:Redux State Not Updated In Dev Tools But Current State Is Being Reflected In PropsRedux 状态未在开发工具中更新,但当前状态正在反映在道具中
【发布时间】:2022-01-14 17:17:13
【问题描述】:

我是一个 redux 菜鸟,想了解 redux 的工作原理。 所以很简单。

我有一家商店

我有一个 reducer,它只返回一个键/对值 {authenticated:false}

我在子组件中有一个 useEffect 函数,每当道具发生变化时,它只是 console.log 的道具值。

子组件以某种方式记录更新的道具,只要它发生更改,但更改不会反映在 redux 开发工具中。

下面是我的代码

index.js

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { Provider } from "react-redux";
import ReduxStore from "./ReduxStore/store";
ReactDOM.render(
  <React.StrictMode>
    <Provider store={ReduxStore}>
      <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById("root")
);

App.js

import { connect, useDispatch } from "react-redux";
const { React, useEffect } = require("react");
const App = (props) => {
  const dispatch = useDispatch();
  useEffect(() => {
   //PS: i intentionally ignored the action dict inside the reducer
    dispatch({ type: "AppReducer", payload: { type: "checkUserToken" } });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    console.log("Props Changed ", props);
// This code above works because it returns the state returned from the reducer anytime it changes
  }, [props]);
  return <>hola </>;
};
const matchStateToProps = (state) => ({ state });
export default connect(matchStateToProps)(App);

store.js

const RootReducer = (state = {}, action) => {
  return {
    authenticated: false,
  };
  
};

const ReduxStore = createStore(RootReducer);
ReduxStore.subscribe(() => console.log("State Is ", ReduxStore.getState()));
export default ReduxStore;

我该如何解决这个问题? 提前致谢

【问题讨论】:

  • FWIW,你真的应该使用our official Redux Toolkit package,这将大大简化你的 Redux 逻辑。这包括存储设置和编写减速器。此外,我们建议使用 React-Redux hooks API 而不是 connect。我建议您通过our Redux docs tutorials 了解如何使用它们。
  • 是的。你的教程不够简单。这很难理解。我知道文档是最好的方法,但它非常令人困惑
  • 很抱歉听到这个消息 :( 不幸的是,大多数在线 Redux 教程都非常过时,并且没有展示如何将“现代 Redux”与 RTK 一起使用。如果您愿意,我仍然建议您尝试通读我们的文档教程可以。

标签: reactjs redux react-redux


【解决方案1】:

我找到了问题的答案。

唯一缺少的代码行是添加

window.__REDUX_DEVTOOLS_EXTENSION__ &amp;&amp; window.__REDUX_DEVTOOLS_EXTENSION__() createStore 参数

代码应该是

const ReduxStore = createStore(
  RootReducer,
  window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);

【讨论】:

  • 请注意,使用 Redux Toolkit,您只需需要 configureStore({reducer: rootReducer}),因为它会自动为您设置 Redux DevTools。
  • 这很有帮助,非常感谢
猜你喜欢
  • 2022-01-14
  • 2020-01-16
  • 2021-11-16
  • 1970-01-01
  • 2017-11-07
  • 2016-09-19
  • 1970-01-01
  • 1970-01-01
  • 2018-01-02
相关资源
最近更新 更多