reactjs - react-redux如何获取provider的store对象?
问题描述
这是一个基本的 react-redux 应用程序(沙箱):
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")
);
现在我的问题是:
hooks 是如何useStore
获取我们设置的 store 对象的<Provider store={store}>
?
如果是dom,我们可以this.closest('.provider').getAttribute('store')
用来获取父元素中provider元素的store属性。但是我们如何在反应中做到这一点?
我问它是因为我想了解 react-redux 在幕后是如何工作的。
谢谢。
解决方案
react-redux
使用一个提供程序,该提供程序包含它使用的所有属性。它允许您通过诸如 hooks API ( useStore
, useDispatch
) 等漂亮的 API 或通过connect()
HOC API 从提供程序中提取内部结构。
为了帮助您以更简单的方式将其可视化,让我们使用 React Context API 编写一个“迷你”react-redux
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>
)
推荐阅读
- google-sheets - 谷歌电子表格添加工作表名称
- javascript - 在Angular中使用ngModel指令选择/取消选择并获取动态生成的复选框的值
- c++ - VSCode 包含路径属性无法正常工作
- asp.net-core - 我想更改 ASP.NET Core 5 MVC 中的路径
- github-actions - 使用 Repository Dispatch API GitHub 给我错误
- react-native - 类型转换表达式应该用括号括起来
- c - 替代在 c 中修改 jmp_buf 以进行上下文切换
- react-native - 反应原生导航 - 在所有屏幕上显示标题选项卡和底部选项卡
- php - 域未在 XAMPP 而不是 localhost 上配置
- html - 固定列长度 - SQLPLUS 输出