首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >redux如何获得提供者的存储对象?

redux如何获得提供者的存储对象?
EN

Stack Overflow用户
提问于 2020-08-07 21:49:39
回答 1查看 523关注 0票数 3

下面是一个基本的redux应用程序(沙盒):

代码语言:javascript
复制
import React from "react";
import ReactDOM from "react-dom";
import { createStore } from "redux";
import { useDispatch, Provider, useSelector, useStore } from "react-redux";
const App = () => {
  const store = useStore(); // <- how it gets the store object of Provider ?
  const state = useSelector(s => s);
  return <div>{state}</div>;
};
ReactDOM.render(
  <Provider store={createStore((state, action) => 5)}>
    <App />
  </Provider>,
  document.getElementById("root")
);

现在我的问题是:

useStore这样的钩子如何获得我们在<Provider store={store}>中设置的存储对象?

如果是dom,我们可以使用this.closest('.provider').getAttribute('store')来获取父母中provider元素的store属性。但我们怎样才能做出反应呢?

我问这个问题是因为我想了解反应-还原在幕后是如何工作的。

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-07 22:13:37

react-redux使用一个提供程序,它保存它所使用的所有属性。它允许您通过漂亮的API (如hooks (useStoreuseDispatch) )或通过connect()临时API从提供者中提取内部信息。

为了帮助您以一种更简单的方式可视化它,让我们使用React上下文API编写一个“迷你”redux。

代码语言:javascript
复制
import React, { createContext, useContext } from 'react';

const InternalProvider = createContext();

/**
 * This is the `Provider` you import from `react-redux`.
 * It holds all of the things child components will need
 */
const Provider = ({ store, children }) => {
  /**
   * This `context` object is what's going to be passed down 
   * through React Context API. You can use `<Consumer>` or 
   * `useContext` to get this object from any react-redux-internal
   * child component.  We'll consume it on our `useStore` and
   * `useDispatch` hooks
   */
  const context = {
    getStore: () => store,
    getDispatch: (action) => store.dispatch,
  };

  return (
    <InternalProvider value={context}>
      {children}
    </InternalProvider>
  );
}


/**
 * These are the hooks you import from `react-redux`.
 * It's dead simple, you use `useContext` to pull the `context`
 * object, and voila! you have a reference.
 */
const useStore = () => {
  const context = useContext(InternalProvider)
  const store = context.getStore();
  return context;
};

const useDispatch = () => {
  const { getDispatch } useContext(InternalProvider);

  return getDispatch();
};


/***************************************
 * Your redux-aware components
 *
 * This is how you consume `react-redux` in your app
 */
const MyComponent = () => {
  const store = useStore();
  const dispatch = useDispatch();

  return <>Foo</>
}

const App = () => (
  <Provider store={store}>
    <MyComponent />
  </Provider>
)
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63309559

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档