简体   繁体   English

在 Reducer 中保存设置并从另一个 Reducer 访问它们?

[英]Saving Settings in Reducer & Accessing them from another Reducer?

I have a settings reducer:我有一个设置减速器:

state = {
    fontSize: 30,
    fontWeight: 400,
    ...etc.
  },

I have a different reducer, which needs access to the fontSize of the settings-reducer.我有一个不同的减速器,它需要访问设置减速器的字体大小。 I don't know now how to access this state now.我现在不知道如何访问这个 state。 What would be an easy & viable solution?什么是简单可行的解决方案?

Based on my understanding through comments,根据我通过评论的理解,

You can achieve what you need as below你可以达到你所需要的如下

  • Keep the initial state fontSize value in both the reducers.在两个减速器中保留初始 state fontSize值。
  • Whenever user updates fontSize of settings reducer by an action , have an another action dispatched with the same value of fontSize to update your article reducer and to calculate new value out of it (You can store it with a different name in article reducer depends on your requirement)每当用户通过action更新设置减速器fontSize时,使用相同的fontSize值调度另一个操作以更新您的文章减速器并从中计算新值(您可以在文章减速器中使用不同的名称存储它取决于您的要求)
  • Now you will be having updated fontSize in settings reducer as per user update, new calculated value based on the updated fontSize in article reducer along with the original (initial) fontSize .现在,您将根据用户更新在设置 reducer中更新fontSize ,新计算值基于article reducer中更新的fontSize以及原始(初始) fontSize
// Assuming you are using thunk middleware

// While dispatching action for fontSize update
updateFontSize (fontSize) {
  return dispatch => {
    dispatch({type: UPDATE_FONT_SIZE, fontSize});
    dispatch({type: GET_UPDATED_FONT_SIZE, fontSize});
  }
}


// settingsReducer.js
const initialState = {
  fontSize: 30,
  fontWeight: 400,
  ...
}

reducer (state = initialState, action) {
  switch(action.type) {
    case UPDATE_FONT_SIZE:
      return {...state, fontSize: action.fontSize};
  ...
}


// articleReducer.js
const initialState = {
  fontSize: 30,
  ...
}

reducer(state = initialState, action) {
  switch(action.type) {
    case GET_UPDATED_FONT_SIZE: // Different action, with different data update based on fontSize
      return {...state, additionalValue: (action.fontSize / 2)};
  ...
}

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

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