gpt4 book ai didi

react-redux - 错误 : An error occured while selecting the store state: Cannot read property 'counter' of undefined

转载 作者:行者123 更新时间:2023-12-04 15:42:39 24 4
gpt4 key购买 nike

App.js

import React from "react";

import { useSelector, useDispatch } from "react-redux";

export const App = () => {
const x = useSelector(state => state.reduserDD.counter);
const dispatch = useDispatch();

console.log(x);

return (
<div>
<div onClick={() => dispatch({ type: "increment" })}>+</div>
<div onClick={() => dispatch({ type: "decrement" })}>-</div>
<div>{x}</div>
</div>
);
};

index.js

import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { createStore } from "redux";

import { App } from "./App";
import { reduserDD } from "./reduser";

const store = createStore(reduserDD);

ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);

reducer

const initialState = {
counter: 0
};

export const reduserDD = (state = initialState, { type }) => {
switch (type) {
case "increment":
return { counter: state.counter + 1 };
case "decrement":
return { counter: state.counter - 1 };
default:
return state;
}
};

我使用 Redux Hook 并收到此错误。

Error: An error occured while selecting the store state: Cannot read >property 'counter' of undefined.

问题是什么,我该如何解决?

最佳答案

您将 reduserDD 直接传递给 createStore。所以 state.reduserDD 不存在。 state 是您的 reduserDD

你只需要获取state.counter而不是state.reduserDD.counter

const x = useSelector(state => state.counter);

关于react-redux - 错误 : An error occured while selecting the store state: Cannot read property 'counter' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57283306/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com