【问题标题】:React/Flux - error propagation from action to store/componentReact/Flux - 从动作到存储/组件的错误传播
【发布时间】:2015-11-07 10:46:37
【问题描述】:

这是一个关于从 react/flux 操作到 store 然后返回到组件的错误传播的问题,错误不是验证,而是尝试更新 store 状态时的 api 调用失败。

这是一个非常简单的例子:

组件:

CityList.jsx
    list of cities is held in a field thats bound to store data field, - This loops over these and writes list of City.jsx:

City.jsx
    Populates the city data to the user, including a toggle button to say whether they have visited or not, e.g:

    name: {this.state.city.name}
    country: {this.state.city.country}
    visited: {this.state.city.visited}

切换“已访问”按钮会触发带有该城市对象的“toggleVisited”操作:

Actions:
    CityActions.js
        toggleVisited(city)
        Takes a city object, makes a request to the api to update the 'visited' value and pushes result to store

Store:
    CityStore.js
        onToggleVisited(city)
        Receives city object from the action and updates the relevant item in its cities array with new value

现在,当 CityActions 中调用的 api 返回错误时会发生什么?如何将其映射到正确的组件以显示适当的错误消息(红色边框、错误文本等)以指示更新失败?

我最初的想法是在 action 中调用 api 之后在 city 对象上设置一个错误字段,然后将其设置回 store 中,看起来像这样:

{
    name: '',
    country: '',
    visited: '',
    error: true
}

(错误可能是一个对象)然后组件将重新渲染城市并

这样组件就可以读取错误字段并在渲染时显示相关的错误消息。

所以:

  • 有没有更好的方法来处理这些错误?
  • 如果我想在页面顶部显示全局错误,没有 无需循环数据即可知道的方法至少检查 {error: true} 的一个实例,然后呈现错误 - 这不是 理想。
  • 有没有办法将错误映射到组件?

【问题讨论】:

    标签: javascript reactjs flux


    【解决方案1】:

    要在页面顶部呈现全局错误,您可以在 CityStore 中存储全局错误消息。
    当 API 的响应包含错误时,您将更新 CityStore 中的全局错误对象。
    当视图随后从 CityStore 获取状态时,您无需遍历所有城市来检查错误。

    您仍然可以将 error: true 保留在城市对象本身中,例如如果您还想在有实际错误的视图中突出显示某个城市。

    【讨论】:

      猜你喜欢
      • 2018-04-16
      • 2017-08-25
      • 2014-11-17
      • 1970-01-01
      • 2015-01-29
      • 2017-06-14
      • 2016-12-16
      • 2014-10-16
      • 2019-09-17
      相关资源
      最近更新 更多