简体   繁体   中英

How to access react-redux store outside of component

I have file which exports various utility functions to use across components, and these functions needs to access redux state. How do I import the state object to this file?

connect does not work here if your utility functions are not react elements.

Best idea is, import create store and then use getState function,

import store from 'store/createStore';
const state = store.getState();

Well, this isn't a simple answer, but after researching this for too long, I found these, which are the only 2 articles that explain anything. They explain how to access the store directly outside of a Component (if you must) and also mention the pure functions / functional programming philosophy as well as potential performance issues with connecting a bunch of non-component functions to the store directly. Personally, I went with @anoop and passed the params around in a single object as deeply as needed.

For connecting directly (which gets the store from this.context the way connect() does, see the discussion here and specifically gaearon's comment on Sep 16, 2015 and Sep 22, 2015. It seems this access can be achieved via connect()

For a little reading on functional programming / pure functions, see the discussion here

The utility should get the state as an argument.

Because you want to use the utility in the components (views) you can store the state in a member variable on your smart component (the one using connect() function) via mapStateToProps(state) callback. then you can pass this member to your dumb components .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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