【发布时间】: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