最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Accessing Store within Redux and React Native app - Stack Overflow

programmeradmin0浏览0评论

I'm starting to develop an app that will be making calls to an API that will require the inclusion of a JWT that I plan on storing within the Redux store.

Typically you can access the Redux store by mapping a particular part of the store to a ponent's state with mapStateToProps() and connect(), however I'd like to access the Redux store within a file that will not end up being a React ponent/container - just a pure js file that will be handling the API calls.

Is this possible?

I'm starting to develop an app that will be making calls to an API that will require the inclusion of a JWT that I plan on storing within the Redux store.

Typically you can access the Redux store by mapping a particular part of the store to a ponent's state with mapStateToProps() and connect(), however I'd like to access the Redux store within a file that will not end up being a React ponent/container - just a pure js file that will be handling the API calls.

Is this possible?

Share Improve this question asked Nov 10, 2016 at 3:26 oldo.nichooldo.nicho 2,2894 gold badges29 silver badges42 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

You can use the getState() function of the store returned by createStore. You can use this inside a function that fishes the needed data from the state.

const myImportantData = () => store.getState().my.deep.data;

The version above uses the store directly, as in a global variable. This prevents you from using more than one store in your process. Normally this is what you want, but this isn't true when running on the server. That said, on the server you'll likely not need the JWT access anyway.

If you do need to swap stores, however, then you can pass it as a parameter or close over a store local variable:

const getDataGrabber = store => () => store.getState().my.deep.data;

Yes, it is possible.

Redux is framework agnostic, although it was made with React in mind.

The mapStateToProps() and connect() methods aren't part of the core Redux library but of the helper library 'React-Redux' which provide bindings specifically for Redux use within React.

It's worth checking out Dan Abramov's Getting started with Redux series to get the principle of how the guts of Redux works.

An example of which are Video 6 and Video 7 where he discusses the Redux store and describes the three methods that make it up:

store.getState  // gets the current application state

store.dispatch  // changes the current application state by dispatching an action

store.subscribe // suscribes to changes and re-renders the app using the
                // current state

The videos go into a fair bit of detail as to how to register the reducers with the store, so the series should prove very helpful.

发布评论

评论列表(0)

  1. 暂无评论