簡體   English   中英

如何在$ .ajax回調函數內的組件視圖中更改變量

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM