在 JavaScript 函数中访问 Redux 存储 [英] Access Redux store in JavaScript function
问题描述
是否可以将 redux 状态映射到常规 javascript 函数而不是 React 组件?
Is it possible to map redux state to a regular javascript function rather than a React component?
如果没有,是否有另一种方法将 redux state 连接到函数?(显然没有明确将其作为参数传入)
If not, is there another way for connecting redux state to a function? (obviously without explicitly passing it in as a param)
我尝试连接到一个函数,但它中断了(我没有确切的错误消息.服务器只是遇到了一个 uncaughtException).由于 React 组件可以是纯函数,connect()
是否只适用于 class ComponentName extends Component
(以及类似的)?
I have tried connecting to a function, but it breaks (I don't have an exact error message. the server just hits an uncaughtException). Since React components can be pure functions, does connect()
only work with a class ComponentName extends Component
(and the likes)?
我想做这样的事情的原因:
The reason I want to do such a thing:
我有一个 redux 动作生成器,如果它发现动作的结果已经处于 redux 状态,我希望生成器跳过执行 API 调用,但我不想必须从每个容器中明确检查每个容器的状态单个 API 调用.这有意义吗?
I have an redux action generator, and I want the generator to skip doing an API call if it finds the action's result already in the redux state, but I don't want to have to check state explicitly from every container for every single api call. Does this make sense?
感谢您的任何想法.
推荐答案
connect()
带有 react-redux
包,它是 Redux 的 React 绑定.但是如果你想用通常的 JavaScript 与 Redux 状态交互,你不需要 connect()
或 react-redux
.您可以通过其 API 直接与 Redux store
交互.
connect()
comes with react-redux
package which is React bindings for Redux. But if you want to interact with Redux state with usual JavaScript you don't need either connect()
or react-redux
for that. You can directly interact with Redux store
with its API.
举个例子,如果你想监听动作,你可以使用 subscribe()
方法如下,并使用 getState()
方法访问 state代码>.
As an example, if you want to listen to actions you can use subscribe()
method as follows and use getState()
method to access the state
.
let unsubscribe = store.subscribe(function(){
const state = store.getState();
})
我不太清楚您要实现的目标,但我希望这会有所帮助.
I'm not much clear what you are trying to achieve, but I hope this will help.
您可以在一个文件中创建您的商店并将其导出.
You can create your store in one file and export it.
store.js
import { createStore } from 'redux'
import reducers from "./reducers";
const store = createStore(reducers)
export default store;
现在您可以从任何其他文件导入商店并使用它.
Now you can import store from any other file and use it.
import store from "./store";
这篇关于在 JavaScript 函数中访问 Redux 存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!