React + Flux:通知视图/组件操作失败?

编程入门 行业动态 更新时间:2024-10-28 01:12:38
本文介绍了React + Flux:通知视图/组件操作失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在编写注册表单组件。当表单提交时,它会触发创建用户操作。 createUser操作通过ajax api调用创建新用户。如果用户已存在,则触发的用户操作将失败。我们知道我们无法从ajax调用返回响应,我们需要回调。我如何告诉我用户已经存在的组件?

I'm writing a Registration Form Component. When form submits it triggers a create user action. createUser actions creates a new user via an ajax api call. If a user already exist, triggered user action fails. We know we cannot return a response from an ajax call, we need a callback for that. How do i tell me component that a user already exists?

// Register From Component var Register = React.createClass({ saveUser : function(event){ event.preventDefault(); userActions.createUser(this.state.user); }, render : function(){ return ( <div className="register-form"> {message} <RegisterForm user={this.state.user} onChange={this.saveUserState} onSave={this.saveUser} errors={this.state.errors} /> </div> ); } }); // Api Ajax call module.exports = { saveUser : function(user) { $.ajax({ type : 'POST', data : { email : user.email, password : user.password }, success: function(res){ } }); }, }; // Actions var UserActions = { createUser : function(user){ var newUser = UserApi.saveUser(user); Dispatcher.dispatch({ actionType : ActionTypes.CREATE_USER, user : newUser }); } };

我想从createUser方法返回一个布尔值。

I was thinking of returning a boolean value from createUser method.

... onSave : function(event){ if(userActions.createUser(this.state.user)){ // } } ...

但我们无法从ajax请求中返回值,如何通知我的组件api未能创建新用户,以便它可以向用户呈现错误消息。

But we cannot return a value from ajax request, how can i notify my component that api has failed to create a new user, so that it can render a error message to user.

推荐答案

使用Promises帮助我处理异步成功/错误处理。我们可以修改 createUser 操作(稍后)触发成功/失败操作,具体取决于用户是否正确保存:

Using Promises has helped me deal with asynchronous success/error handling. We can modify the createUser action to (at a later time) trigger success/failure actions depending on if the user was saved correctly or not:

// Actions var UserActions = { userCreated : function(user) { Dispatcher.dispatch({ actionType : ActionTypes.CREATE_USER, user : user }); }, createUserFailed : function() { Dispatcher.dispatch({ actionType : ActionTypes.CREATE_USER_FAILED }); }, createUser : function(user) { // You should update the saveUser method to return a Promise that // resolves the new user on success and rejects on failure // (ie if the user already exists). Alternatively, you could update // this function to accept success/error callbacks. UserApi.saveUser(user) .then(this.userCreated.bind(this)) .catch(this.createUserFailure.bind(this)); } };

更多推荐

React + Flux:通知视图/组件操作失败?

本文发布于:2023-10-30 02:59:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1541562.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:视图   组件   操作   通知   React

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!