简体   繁体   English

根据reactjs中的条件设置状态

[英]setting state based on conditional in reactjs

I have a simple API call that sets the state of a list array with its response. 我有一个简单的API调用,它使用响应设置列表数组的状态。 I was wondering how I would go about implement a try/catch or error message if there is a bad search (ie like a typo) or if the array is not set with the response. 我想知道如果搜索不正确(如错字)或数组未设置响应,该如何执行try / catch或错误消息。 The code snippet is below: 该代码段如下:

componentDidMount() {
    this.search('https://itunes.apple.com/search?term=modern_baseball');
}

search(URL) {
   return $.ajax({
        type: 'GET',
        dataType: 'json',
        url: URL,
        success: function (response) {
            this.showResults(response);
        }.bind(this),
        error: function() {
            alert("Error handling request");
        }
    });
}

showResults(response) {
    console.log(response);
    this.setState({
        searchResults: response.results,
        moveResults: []
    });
}

Try something like this: 尝试这样的事情:

componentDidMount() {
    this.search('https://itunes.apple.com/search?term=modern_baseball');
}

search(URL) {
  let self = this; //avoid the .bind call and store a ref to the current context for use inside the ajax handlers.
   return $.ajax({
        type: 'GET',
        dataType: 'json',
        url: URL,
        success: function (response) {
            self.showResults(response);
        },
        error: function() {
            alert("Error handling request");
            self.setState({error: "Error handling request", moveResults:[], searchResults:[]}); //set the state directly if there is an error
        }
    });
}

showResults(response) {
    console.log(response);
    this.setState({
        searchResults: response.results,
        moveResults: []
    });
}

It sets a variable (self) to the current context (this) and then calls the setState directly in the error handler for the ajax call. 它为当前上下文(this)设置一个变量(自身),然后直接在ajax调用的错误处理程序中调用setState。 Alternatively you could define a callback function just like you do for the success handler. 另外,您可以定义回调函数,就像对成功处理程序所做的一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM