【发布时间】: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