简体   繁体   English

在 JavaScript 函数中访问 Redux 存储

[英]Access Redux store in JavaScript function

Is it possible to map redux state to a regular javascript function rather than a React component?是否可以将 redux 状态映射到常规 javascript 函数而不是 React 组件?

If not, is there another way for connecting redux state to a function?如果没有,是否有另一种方法将 redux 状态连接到函数? (obviously without explicitly passing it in as a param) (显然没有明确地将它作为参数传入)

I have tried connecting to a function, but it breaks (I don't have an exact error message. the server just hits an uncaughtException).我曾尝试连接到一个函数,但它中断了(我没有确切的错误消息。服务器只是遇到了 uncaughtException)。 Since React components can be pure functions, does connect() only work with a class ComponentName extends Component (and the likes)?由于 React 组件可以是纯函数, connect()仅适用于class ComponentName extends Component (等等)?

The reason I want to do such a thing:我想做这样的事情的原因:

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.我有一个 redux 动作生成器,如果它发现动作的结果已经处于 redux 状态,我希望生成器跳过执行 API 调用,但我不想为每个单独的 api 调用从每个容器中明确检查状态. Does this make sense?这有意义吗?

Thanks for any ideas.感谢您的任何想法。

connect() comes with react-redux package which is React bindings for Redux. connect()带有react-redux包,它是 Redux 的 React 绑定。 But if you want to interact with Redux state with usual JavaScript you don't need either connect() or react-redux for that.但是如果你想用通常的 JavaScript 与 Redux 状态交互,你不需要connect()react-redux You can directly interact with Redux store with its API .您可以通过其API直接与 Redux store交互。

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 .例如,如果你想监听动作,你可以使用subscribe()方法如下,并使用getState()方法访问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.我不太清楚您要实现的目标,但我希望这会有所帮助。

Edit:编辑:

You can create your store in one file and export it.您可以在一个文件中创建您的商店并将其导出。

store.js商店.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.现在您可以从任何其他文件导入 store 并使用它。

import store from "./store";

Suppose you have an action.假设你有一个动作。 Just add some marker - and the reducer will detect whether skip that or not:只需添加一些标记 - 并且减速器将检测是否跳过该标记:

Action:
{
  type: 'SOMETYPE',
  paylod: data,
  shouldSkip: true
}

Reducer:
export default function ( state = {}, action ) {
  if(action.shouldSkip)
    return state
  switch ( action.type ) {
    case "OTHER_TYPE":
      return action.payload;
    default:
      return state;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM