reactjs - 不处理缺失的细节,响应 False
问题描述
当标题不存在时,如何检查是否发出警报?
这可以用axios实现吗?
export const getMoviesImdb = async (title) => {
title = encodeURIComponent(title);
return fetch(`http://www.omdbapi.com/?s=${title}`)
.then((response) => response.json()
.then((data) => {
if (data.Response != "False") {
return data.Search
}
return Promise.reject(data.Message);
}, [])
.catch((error) => {
return Promise.reject(error);
})
);
};
解决方案
使用 axios,您可以使用response.data
. 此外,它已经返回了一个 Promise,因此您不必显式地返回 Promise。而是检查 api 响应并抛出错误,然后在使用中(调用getMoviesImdb
函数的地方)简单地捕获它。最后,getMoviesImdb
乐趣不必是异步的乐趣。
工作演示(只需在 url 中添加您的 api 密钥进行测试)
代码片段示例
export default function App() {
useEffect(() => {
let myMovies;
getMoviesImdb("asdf")
.then(res => {
// make sure to use your api key to see results
console.log("res", res);
myMovies = res;
})
.catch(err => {
// make sure to use your api key to see error message
console.log("err", err);
});
}, []);
const getMoviesImdb = title => {
console.log("title", title);
// title = encodeURIComponent(title);
// use your api key below
return axios(`http://www.omdbapi.com/?s=${title}`).then(response => {
// console.log("response", response);
if (response.data.Response !== "False") {
return data.Search;
}
console.log("response.data", response.data.Error);
throw new Error(response.data.Error);
});
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
推荐阅读
- flutter - Flutter GridView item wrap_content 高度
- php - sql 命令成功后刷新页面
- google-sheets - 有没有办法将 YouTube 播放列表中的视频名称导入 Google 表格?
- javascript - 如果存储为对象,如何检索数据?
- class - 公共方法中的私有方法
- c++ - 类/结构/联合中的匿名类/结构/联合是什么意思?
- c# - 带有 Application Insights 目标的 NLog 不记录自定义参数和异常
- r - 获取字符串中某个单词出现频率的通用函数
- c - 在c中连接两个动态分配的char数组
- selenium - 引起:org.openqa.selenium.InvalidSelectorException: