如何使用CreateSelectorHook()
我在 codesandboxboxboxboxboxbox :无法读取未定义的属性(读取'getState')
使用 createSelectorHook()?有人可以创建一个代码框来说明其用法吗?
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为React-Redux v8.0.0删除了
defaultrootState
(推断状态):来源:发行笔记
so,
streateStorehook
如果您想(a)绑定到自定义上下文或(b)确保呼叫usestate()。
返回正确键入的redux商店。请注意,如果这是(b)的正确甚至建议的用例,我不是积极的。我还发现,这是按照
useAppdisPatch
的记录示例的工作作用的:I think react-redux v8.0.0 removed
DefaultRootState
(inferring the state):source: the release notes
So,
createStoreHook
appears to exist if you'd like to (a) bind to a custom context or, (b) ensure a call to something likeuseState().getStore()
returns a properly typed redux store.Note, I am not positive, if this is a correct or even suggested use case for (b). I also discovered that this works following the documented example for
useAppDispatch
:在Redux 4.0中,“ createstore”被弃用,您可以使用“ configurestore”。请参阅以下代码:
In Redux 4.0 "createStore" is been deprecated, You can use "configureStore" instead. please refer to the below code :