基于reactjs中的条件设置状态

时间:2017-07-13 15:58:10

标签: javascript reactjs

我有一个简单的API调用,用它的响应设置列表数组的状态。我想知道如果有一个糟糕的搜索(比如拼写错误)或者数组未设置响应,我将如何实现try / catch或错误消息。代码段如下:

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: []
    });
}

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

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: []
    });
}

它将变量(self)设置为当前上下文(this),然后直接在错误处理程序中调用setState以进行ajax调用。或者,您可以像成功处理程序一样定义回调函数。