【问题标题】:Saving Settings in Reducer & Accessing them from another Reducer?在 Reducer 中保存设置并从另一个 Reducer 访问它们?
【发布时间】:2020-11-25 12:30:01
【问题描述】:

我有一个设置减速器:

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

我有一个不同的reducer,它需要访问settings-reducer 的fontSize。我现在不知道如何进入这个状态。什么是简单可行的解决方案?

【问题讨论】:

  • 为什么需要从减速器 B 访问减速器 A?业务是什么?
  • 您可以选择将其移动到单独的文件并导入到两个减速器中。
  • 我怎么能这样做@PrathapReddy?到目前为止,我发现的所有内容都将逻辑巧妙地分开。我可以以某种方式将 settings-reducer 的状态导入到我当前的 reducer 中吗?
  • 这些设置是否因某种操作而改变?你想收听这些设置的更新吗?
  • 是的,完全正确。用户可以更改字体大小,这会反映在应用程序中。我有一个用于所有设置的减速器和一个用于文章的减速器。现在的问题不是在设置减速器中更改字体大小时更改屏幕上的字体大小,问题是我的另一个减速器需要字体大小来计算一些东西。 (我知道这可能不是最佳实践,但出于其他原因还是选择了这种架构)

标签: javascript reactjs redux react-redux flux


【解决方案1】:

根据我通过cmets的理解,

你可以实现你所需要的如下

  • 在两个 reducer 中保持初始状态 fontSize 值。
  • 每当用户通过 action 更新 settings reducerfontSize 时,调度另一个具有相同值 fontSize 的操作来更新您的 article reducer并从中计算出新值(根据您的要求,您可以在 article reducer 中以不同的名称存储它)
  • 现在您将根据用户更新在 settings 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)};
  ...
}

【讨论】:

    猜你喜欢
    • 2017-03-07
    • 2017-04-02
    • 1970-01-01
    • 2019-04-01
    • 2016-06-21
    • 2020-05-30
    • 2016-12-01
    • 1970-01-01
    • 2020-02-16
    相关资源
    最近更新 更多