});
}
还会发生出请求出错的情况:
function onSearch(keyword) {
this.setState({
isLoading: true,
});
fetch(SEARCH_URL + “?keyword=” + keyword)
.then((data) => {
this.setState({ data, isLoading: false });
})
.catch((e) => {
this.setState({
isError: true,
});
});
}
当然,不能忘记把 Loading 关掉:
function onSearch(keyword) {
this.setState({
isLoading: true,
});
fetch(SEARCH_URL + “?keyword=” + keyword)
.then((data) => {
this.setState({ data, isLoading: false });
})
.catch((e) => {
this.setState({
isError: true,
isLoading: false,
});
});
}
我们每次搜索时,还需要把错误清除:
function onSearch(keyword) {
this.setState({
isLoading: true,
isError: false,
});
fetch(SEARCH_URL + “?keyword=” + keyword)
.then((data) => {
this.setState({ data, isLoading: false });
})
.catch((e) => {
this.setState({
isError: true,
isLoading: false,
});
});
}
这就结束了么,是不是我们把所有的 Bug 都考虑进去了?并没有。当用户在等待搜素请求的时候,不应该再去搜索,所以搜索结果返回前,禁止再次发送请求:
function onSearch(keyword) {
if (this.state.isLoading) {
return;
}
this.setState({
isLoading: true,
isError: false,
});
fetch(SEARCH_URL + “?keyword=” + keyword)
.then((data) => {
this.setState({ data, isLoading: false });
})
.catch((e) => {
this.setState({
isError: true,
isLoading: false,
});
});
}
可以看到,应用的复杂度在不断变大,可能你经历的场景比这个小示例还要复杂的多的多。如果因为搜索接口特别慢,用户希望有一个中断搜索的功能,那么新的需求又来了:
function onSearch(keyword) {
if (this.state.isLoading) {
return;
}
this.fetchAbort = new AbortController();
this.setState({
isLoading: true,
isError: false,
});
fetch(SEARCH_URL + “?keyword=” + keyword, {
signal: this.fetchAbort.signal,
})
.then((data) => {
this.setState({ data, isLoading: false });
})
.catch((e) => {
this.setState({
isError: true,
isLoading: false,
});
});
}
function onCancel() {
this.fetchAbort.abort();
}
不能落下对 catch 的特殊处理,因为中断请求会触发 catch:
function onSearch(keywo