【问题标题】:Validation handling in reduxredux 中的验证处理
【发布时间】:2018-12-12 16:23:06
【问题描述】:

考虑像这样的减速器(我正在使用redux-action 库)

export const reducer = handleActions({
  [REMOVE_CATEGORY]: (state, action) => ({
    ...state,
    // Do other stuff...
  }),
  [TOGGLE_CATEGORY]: (state, action) => {
    const category = action.payload.category
    const selectedCategory = _.findWhere(state.categories, {name: category.name})
    const activeCategories = _.filter(state.categories, {active: true})

    if (activeCategories.length < 4 && selectedCategory.active === true) {
      return {
        ...state,
        didToggleFail: true
      }
    }

    return {
      didToggleFail: false,
      isRequesting: false,
      categories: state.categories.map(
        category => category.name === action.payload.category.name ? {...category, active: !category.active} : category
      )
    }
  },
  [OTHER_ACTION]: (state,action) => ({
    ...state, 
    // Do other stuff..
  })
})

我发现自己面临一个简单的问题,这可能来自我对解决方案的错误方法;

我的 reducer 中的每个 action 基本上都传播了预先存在的状态,但是有一个字段 didToggleFail 是根据各种条件设置的。

现在我的问题是:didToggleFail 我用于同步验证,将永远处于我的状态,直到未设置。

我在componentDidUpdate 中使用didToggleFail,如下所示:

componentDidUpdate() {
if(this.props.reducer.didToggleFail)
   showError() 
}
...

如您所见,我的问题是,如果我调度其他操作并且该字段仍设置为true,它将始终触发错误。

这种情况应该如何处理?

【问题讨论】:

    标签: reactjs error-handling redux


    【解决方案1】:

    我猜在显示错误后,将向用户提供关闭它的选项(或超时后自动关闭)。此时,派另一个UNSET_TOGGLE_FAILdidToggleFail 设置为false。这应该防止多个触发器。

    但是,最佳解决方案取决于showError() 所做的事情。它是渲染方法还是另一个 redux 操作调度。如果是纯渲染,我建议在组件的render 内移动,因为每次重新渲染后都会调用componentDidUpdate,如果你不取消设置didToggleFail,它可能会导致循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-09
      • 2019-11-16
      • 1970-01-01
      • 2021-09-02
      • 2022-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多