我在CodeSandbox上收到此错误:无法读取未定义的属性(阅读“getState”)
什么是正确的方式来使用codeSelectorHook()?有人可以创建一个CodeSandbox来说明它的用法吗?
index.js:
import React from "react";
import { createRoot } from "react-dom/client";
import { createStore } from "redux";
import reducer from "./reducer";
import App from "./App";
import myContext from "./context";
import {
Provider,
createStoreHook,
createDispatchHook,
createSelectorHook
} from "react-redux";
export const useStore = createStoreHook(myContext);
export const useDispatch = createDispatchHook(myContext);
export const useSelector = createSelectorHook(myContext);
const store = createStore(reducer, 0);
const root = createRoot(document.getElementById("root"));
root.render(
<Provider store={store} context={myContext}>
<App />
</Provider>
);
字符串
App.js:
import React, { useState, useRef } from "react";
import { useSelector, useDispatch } from "./";
import context from "./context";
const Counter = (props) => {
return (
<context.Provider value={props}>
<A />
</context.Provider>
);
};
const A = (props) => {
return <B />;
};
const B = (props) => {
return <C />;
};
const C = (props) => {
const v = useSelector((state) => state);
const dispatch = useDispatch();
return (
<div>
<button onClick={() => dispatch({ type: "DECREMENT" })}>-</button>
value:<span>{v}</span>
<button onClick={() => dispatch({ type: "INCREMENT" })}>+</button>
</div>
);
};
const App = () => {
const stepInput = useRef(1);
const [step, updateStep] = useState(1);
return (
<div>
step:
<input
ref={stepInput}
type="number"
onChange={() => updateStep(stepInput.current.value)}
/>
<Counter step={step} />
</div>
);
};
export default App;
型
2条答案
按热度按时间ktecyv1j1#
我认为react-redux v8.0.0删除了
DefaultRootState
(推断状态):字符串
source: the release notes
因此,如果您希望(a)绑定到自定义上下文,或者(b)确保对
useState().getStore()
之类的调用返回正确类型的redux store,则createStoreHook
似乎存在。请注意,我不确定这是否是(B)的正确用例,甚至是建议的用例。我还发现,按照
useAppDispatch
的文档示例,这是可行的:型
cig3rfwq2#
在Redux 4.0中,“configureStore”已被弃用,您可以使用“configureStore”代替。请参考以下代码:
字符串