【问题标题】:Reducer that updates multiple parts of the state更新状态的多个部分的 Reducer
【发布时间】:2017-03-26 06:45:17
【问题描述】:

实际上,我每次更新state.thickness 时都需要更新state.litres。我怎么做? (我用“state”这个词来表示redux store)

这是我的减速器:

export const thickness = (
  initialThickness: Map<*, *> = initialState.get('thickness'), 
  action: Object) => {
  switch(action.type) {
    case 'UPDATE_THICKNESS': {
      const litres = calcVol(action.payload.state)
      let newThickness = initialThickness
        .set('thickness' + action.payload.number, action.payload.value)
      return newThickness
    }
    default:
      return initialThickness
  }
}

litres 是我刚刚添加的内容,我想将它和newThickness 一起返回 - 这是我在更新state.thickness 时尝试更新state.litres

如果你能对此发表意见,加分:为了计算升,我需要访问整个状态(redux 存储)以传递给calcVol(state)(它计算并返回以升为单位的体积)。像这样在action 中传递整个状态,以便我可以在reducer 中使用它,性能好吗?还是有更高效的方法?

const mapDispatchToProps = (dispatch) => ({
  updateThickness: (text, number, state) => {
    dispatch(updateDimension('thickness', text, number, state))
  }
})

【问题讨论】:

    标签: reactjs react-native redux react-redux


    【解决方案1】:

    像这样的 reducer 不能同时更新 thicknesslitres,因为它只能影响它负责的节点(在这种情况下为 thickness)。您可以:

    1. 将reducer向上移动一个级别并让它拥有thicknesslitres节点,即initialState = { thickness: 0, litres: 0 }
    2. litres 减速器也处理 UPDATE_THICKNESS 动作类型并相应地更新 litres

    但是,您也没有理由不能同时调度 'UPDATE_LITRES' 操作。如果您使用像 redux-thunk 这样的中间件,那么这会更容易,因为您可以从同一个 thunk 中进行调度,并且它还可以消除在操作中传递整个状态的需要(我不建议这样做,但没有数字支持)。

    const setThickness = (number, value) => {
        return (dispatch, getState) => {
            dispatch({ type: 'UPDATE_THICKNESS': payload: { number, value } })
    
            let litres = calcVol(getState())
            dispatch({ type: 'UPDATE_LITRES': payload: { number, value: litres } })
        }
    }
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-28
      • 2023-01-28
      • 2018-03-12
      • 2016-12-01
      • 2019-02-25
      • 2018-08-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多