处理Axios中的错误。在React/JS中收到的数据
我正在努力弄清楚如何在从API获取数据后防止我的应用程序崩溃。这是我到目前为止所做的:
用户搜索一个单词并基于该单词,该程序转到带有搜索短语的链接,然后获取并将数据存储在const
var baseUrl = `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=${search}&apikey=****`;
$ {search}
= =无论用户进入搜索栏中的任何内容
,baseUrl都是用于从API获取所有数据的网站
useEffect(() => {
axios.get(baseUrl)
.then(res => {
setChart(res.data);
// console.log(res.data)
})
.catch(error => {
console.log("there was an error: " + error);
})
}, [baseUrl]);
useEffect(()=>{}, [chart]);
,然后程序循环通过API循环,并存储每个条目的日期和价格。
const stockPrices = useMemo(() => chart && Object.values(chart['Time Series (Daily)']).map(i => i['1. open']).reverse(), [chart]);
const stockDates = useMemo(() => chart && Object.keys(chart['Time Series (Daily)']).map(x => x.replace(/\d{4}-/, "")).reverse(), [chart]);
但是,有时,如果用户输入没有现有链接的搜索。该应用程序崩溃了,因为它试图循环并显示不存在的数据。
我不太确定该如何处理。
在搜索组件中,如果搜索为空(因为不存在此类链接),我添加了这个小的“ IF”语句,以停止它做任何事情:
const handleSearch = (e) => {
e.preventDefault();
if (e.target.value !== ``) {
setSearch(e.target.value.toUpperCase())
}};
但是,这仅解决了问题的一小部分。如果该应用程序试图从无效链接中获取数据,则只会崩溃。
当应用崩溃时 - 在控制台中说 "Cannot convert undefined or null to object" which is reported from the line where const stockPrices and const stockDates are sitting on.
如果不存在链接,我该如何阻止该应用程序获取数据 - 如何处理此错误?
仅对于上下文,然后传递了这些变量中存储的数据以渲染以价格(y轴)和日期(x轴)的图表,因此它至少需要进行某种替换
if(typeof stockDates === 'undefined') {
return ('undefined');
} else if(stockDates=== null){
return ('null');
}
。用“ null”获取|| “未定义”,但仍在崩溃。
请帮忙。
简称:应用程序崩溃,如果它试图从不存在的链接中获取数据(基于搜索栏的输入)
I'm struggling to figure out how to prevent my app from crashing after fetching data from an API. Here's what I have done so far:
User searches for a word and based on that word, the program goes to a link with the searched phrase, then fetches and stores data in a const
var baseUrl = `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=${search}&apikey=****`;
${search}
= whatever the user enters in the searchbar
then baseUrl is the webite used to get all the data from API
useEffect(() => {
axios.get(baseUrl)
.then(res => {
setChart(res.data);
// console.log(res.data)
})
.catch(error => {
console.log("there was an error: " + error);
})
}, [baseUrl]);
useEffect(()=>{}, [chart]);
then the program loops thru the API and stores DATE and PRICE for each entry in const stockPrices and stockDates.
const stockPrices = useMemo(() => chart && Object.values(chart['Time Series (Daily)']).map(i => i['1. open']).reverse(), [chart]);
const stockDates = useMemo(() => chart && Object.keys(chart['Time Series (Daily)']).map(x => x.replace(/\d{4}-/, "")).reverse(), [chart]);
However, sometimes if user enter a search for which there's no existing link.. the app crashes, as it's trying to loop and display data that doesn't exist.
I'm not really sure how to handle this.
In the search component, I added this little "if" statement to stop it doing anything if the search is empty ( because no such link exists ):
const handleSearch = (e) => {
e.preventDefault();
if (e.target.value !== ``) {
setSearch(e.target.value.toUpperCase())
}};
However, this only solves a small part of the problem. If the app tries to fetch data from an invalid link it simply crashes.
when the app crashes - in the console it says
"Cannot convert undefined or null to object" which is reported from the line where const stockPrices and const stockDates are sitting on.
How can I stop the app from fetching data if a link doesn't exist - how to handle this bug ?
just for context the data stored in those variables is then passed to render a chart with prices (Y-axis) and dates(X-axis) so it needs to at least have some sort of replacement..
if(typeof stockDates === 'undefined') {
return ('undefined');
} else if(stockDates=== null){
return ('null');
}
I tried doing this to replace bad fetch with 'null' || 'undefined' but it's still crashing.
Please help.
IN SHORT: App crashes if it's trying to fetch data from a link that doesn't exist ( based on input from searchbar )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定您在搜索问题上面临什么错误。
另一个是您将
不确定
object.keys.keys 或object.values.values
函数进行的错误。我猜该API返回了一些无效链接的数据,因此图表并不是未定义的。在代码中,您正在检查以确保
Chart
不是未定义的。但最有可能的是,图表['时间序列(每日)']
是未定义的。我对您的要求不太了解,无法提出修复。但是您可以添加额外的检查并做到……
但是我认为修复获取代码会更好。
I'm not sure what error you're facing with the search problem.
The other one's the error you get when you pass
undefined
toObject.keys
orObject.values
function.I'm gonna guess the API returns some data for invalid links so chart is not undefined. In the code, you're checking to make sure
chart
is not undefined. But most likely,chart['Time Series (Daily)']
is undefined.I don't know enough about your requirements to suggest a fix. But you could add an additional check and make it so...
But I think it'd be better to fix the fetch code.