简体   繁体   中英

Reactjs + redux : Sharing reducers across different components

I am basically trying to create a react webapp with lot of pages. And the data for each page is loaded through different API calls. And most response have information dependent on each other. I decided to use redux to store these response and access from each components.

This is what my reducer file look like,

var initialState = {
      "userDetails": [],
      "userPicks": []
    };

module.exports = function(state, action, data) {
  state = state || initialState;
  switch (action.type) {
    case 'ADD_USER_LIST':
      return Object.assign({}, state, {
        "userDetails": action.data
      })

    case 'ADD_USER_PICK_LIST':
      return Object.assign({}, state, {
        "userPicks": action.data
      })

    case 'UPDATE_SELECTION':
      return Object.assign({}, state, {
        return "do something"
      });

    default:
      return state
  }
}

So I use

var redux = require('redux'); var reducers = require('./reducers'); var store = redux.createStore(reducers);

on top of each component that uses information from store.

store.getState()

but this process always resets my reducer state to initial one and the app loses all data. Can anyone point out where I am wrong and what I should be looking in to?

"Can anyone point out where I am wrong " you are creating new store for every component type. You need to make it a separate module and create store once per application.

// redux/store js
var redux = require('redux');
var reducers = require('./reducers');
module.exports = redux.createStore(reducers);

"what I should be looking in to" you should take a look at official react binding for redux. React Redux .

// app.js
var store = require('./redux/store.js');
var Provider = require('react-redux').Provider

ReactDOM.render(
 (<Provider store={store}>
     <App />
  </Provider
 ), mountingPoint)

You have to create redux store once in your toplevel app

var redux = require('redux');
var reducers = require('./reducers');
var store = redux.createStore(reducers);

Dont create for every compnent. Use container components to mapStatetoProps and mapDispatchToProps and pass props to the 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