我正在编写注册表单组件。当表单提交时,它会触发创建用户操作。 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:通知视图/组件操作失败?
发布评论