如何使用CreateSelectorHook()

发布于 2025-01-22 00:07:59 字数 2239 浏览 1 评论 0 原文

我在 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;

I am receiving this error on CodeSandbox: Cannot read properties of undefined (reading 'getState')

What is the proper way to use createSelectorHook()? Could someone please create a CodeSandbox to illustrate its usage?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

爱的那么颓废 2025-01-29 00:07:59

我认为React-Redux v8.0.0删除了 defaultrootState (推断状态):

Now that React-Redux itself is written in TS, we've opted to remove the DefaultRootState type entirely. State generics now default to unknown instead.

来源:发行笔记

so, streateStorehook 如果您想(a)绑定到自定义上下文或(b)确保呼叫 usestate()。 返回正确键入的redux商店。

请注意,如果这是(b)的正确甚至建议的用例,我不是积极的。我还发现,这是按照 useAppdisPatch 的记录示例的工作作用的:

export const useAppStore = () => useStore<RootState>();

I think react-redux v8.0.0 removed DefaultRootState (inferring the state):

Now that React-Redux itself is written in TS, we've opted to remove the DefaultRootState type entirely. State generics now default to unknown instead.

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 like useState().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:

export const useAppStore = () => useStore<RootState>();
醉殇 2025-01-29 00:07:59

在Redux 4.0中,“ createstore”被弃用,您可以使用“ configurestore”。请参阅以下代码:

import React from 'react';
import App from './App';
import { configureStore } from '@reduxjs/toolkit';
let initialState = {
 counter: 0,
};
function counterReducer(state = initialState, action) {
 if (action.type === 'increment') {
    return { counter: state.counter + 1 };
 } else if (action.type === 'decrement') {
    return { counter: state.counter - 1 };
 } else {
    return state;
 }
}
const store = configureStore({
 reducer: counterReducer,
 preloadedState: initialState,
});
console.log(store.getState, 'redux store');
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
 <React.StrictMode>
    <App />
 </React.StrictMode>
);

In Redux 4.0 "createStore" is been deprecated, You can use "configureStore" instead. please refer to the below code :

import React from 'react';
import App from './App';
import { configureStore } from '@reduxjs/toolkit';
let initialState = {
 counter: 0,
};
function counterReducer(state = initialState, action) {
 if (action.type === 'increment') {
    return { counter: state.counter + 1 };
 } else if (action.type === 'decrement') {
    return { counter: state.counter - 1 };
 } else {
    return state;
 }
}
const store = configureStore({
 reducer: counterReducer,
 preloadedState: initialState,
});
console.log(store.getState, 'redux store');
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
 <React.StrictMode>
    <App />
 </React.StrictMode>
);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文