过去几个月里,我一直在学习React and Flux,有一件我还没有处理的问题是向用户显示错误信息.具体来说,作为通量动作创建者方法中的ajax http请求的结果而发生的错误消息.
一个简单的例子是用户登录 – 如果ajax请求的登录由于密码不正确而失败,则服务器会以失败方式进行响应.在那一刻,在我的助动作创建者方法中,我唯一的选择是发送一个包含错误信息的动作,对吧?
我可以发送错误信息并将该错误保存在商店中.我不知道把某些错误与某些组件绑在一起的最佳方法是.说我的反应组件树正在呈现多个错误感知组件,但在服务器端用户身份验证尝试期间发生错误,需要在该登录表单上显示.
有没有很好的模式或惯例存储错误,并知道他们是哪个组件?是否有一种程序化的方式来确定这一点,而不是将一些标识符传递给每个动作创建者功能,以识别动作创建者称之为组件等等?
解决方法
由于您使用Redux标记标记问题,我假设您使用Redux.
如果是这样,这个 real-world example显示错误处理.
如果是这样,这个 real-world example显示错误处理.
有一个reducer that reacts to any action with error
field:
- // Updates error message to notify about the Failed fetches.
- function errorMessage(state = null,action) {
- const { type,error } = action;
- if (type === ActionTypes.RESET_ERROR_MESSAGE) {
- return null;
- } else if (error) {
- return action.error;
- }
- return state;
- }
自定义API中间件puts any error message into error
field on the action:
- return callApi(endpoint,schema).then(
- response => next(actionWith({
- response,type: successType
- })),error => next(actionWith({
- type: failureType,error: error.message || 'Something bad happened'
- }))
- );
最后组件reads the error message from Redux store:
- function mapStateToProps(state) {
- return {
- errorMessage: state.errorMessage
- };
- }