![](/img/trans.png)
[英]How exactly do I write a callback function to change a global variable inside AJAX for jquery?
[英]How to change a variable in the component view inside the callback function of $.ajax
我一直试图将ajax请求返回的“错误”数据传递给“ this.state.errorMessage”,并在视图中进行渲染。
let getListState = () => {
return {
requestState: InviteStore.getRequestState()
};
}
@withStyles(styles)
class InvitePage extends React.Component {
constructor() {
super();
this.state = {};
this.state.errorMessage = "temp";
}
_onChange() {
this.setState(getListState());
this.state = {};
console.log("REQ STATE : "+ InviteStore.getRequestState());
}
componentDidMount() {
InviteStore.addChangeListener(this._onChange.bind(this));
console.log("EVENT STATE :" + InviteStore.getRequestState());
}
componentWillUnmount() {
InviteStore.removeChangeListener(this._onChange.bind(this));
console.log("EVENT STATE UN :" + InviteStore.getRequestState());
}
getErrorMessage()
{
return this.state.errorMessage;
}
sendInvitation(e)
{
e.preventDefault();
let email_address = ReactDOM.findDOMNode(this.refs.email_address).value.trim();
ReactDOM.findDOMNode(this.refs.email_address).value = '';
console.log(email_address);
var self = this;
$.ajax({
type: ApiRoutes.routes.subscribe.type,
url: ApiRoutes.routes.subscribe.url,
data: {email: email_address},
success: function(response){
self.setState("requestState", "success");
self.setState("token", response.data.token);
}
})
.fail(function(response) {
var temp = $.parseJSON(response.responseText);
self.state.errorMessage = "error";
});
}
render() {
return(
<div className={classnames('InvitePage', this.props.type)}>
<h1>Request Invitation</h1>
<form onSubmit={this.sendInvitation.bind(this)}>
<input name="email_address" type="text" ref="email_address" placeholder="Enter your email" />
<button className="button primary">Submit</button>
{this.getErrorMessage()}
</form>
</div>
);
}
}
export default InvitePage;
我假设您的侦听器设置正确(例如,您确定没有丢失事件吗?InviteStore.addChangeListener('change',this._onChange.bind(this)););
否则,您将this.state放入一个空对象,这就是为什么您无法访问状态的原因。
_onChange() {
this.setState(getListState());
//this.state = {}; delete this line, why this.state = {} ?
console.log("REQ STATE : "+ InviteStore.getRequestState());
}
希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.