简体   繁体   English

Reactjs + Redux:在不同组件之间共享化简

[英]Reactjs + redux : Sharing reducers across different components

I am basically trying to create a react webapp with lot of pages. 我基本上是想创建一个包含很多页面的React Webapp。 And the data for each page is loaded through different API calls. 每个页面的数据通过不同的API调用加载。 And most response have information dependent on each other. 并且大多数响应具有彼此依赖的信息。 I decided to use redux to store these response and access from each components. 我决定使用redux来存储每个组件的响应和访问。

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. “我应该关注的是”您应该看看redux的官方React绑定。 React Redux . 反应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 您必须在顶级应用中创建一次Redux存储

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 使用容器组件来mapStatetoProps和mapDispatchToProps并将prop传递给组件

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

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