Access Redux store in JavaScript function

后端 未结 2 501
我寻月下人不归
我寻月下人不归 2021-02-08 09:38

Is it possible to map redux state to a regular javascript function rather than a React component?

If not, is there another way for connecting redux state to a function?

相关标签:
2条回答
  • 2021-02-08 10:10

    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;
      }
    }
    
    0 讨论(0)
  • 2021-02-08 10:19

    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.

    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.

    Edit:

    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";
    
    0 讨论(0)
提交回复
热议问题