我正在React中建立一个股票应用程序项目,遇到了我一直试图解决的问题,但是没有成功。真的可以使用一些帮助,因为我知道我很亲近。该代码附在图片中,我还将在此处发布:
// Search Stocks
const searchStocks = async () => {
// await data from API
const res = await axios(`https://financialmodelingprep.com/api/v3/searchquery=${state.text}&exchange=NASDAQ`);
const res2 = await axios(`https://financialmodelingprep.com/api/v3/searchquery=${state.text}&exchange=NYSE`);
// after data has returned in variables, then filter results
const filteredResults = [...res, ...res2].filter(stock => stock.symbol.includes(state.text.toUpperCase()))
// dispatch to have filtered results added to state to show the user
dispatch({
type: SEARCH_STOCKS,
payload: filteredResults
});
};
因此,我对我的方法进行了两次和三次检查,以确保我正确地过滤了数据。我知道逻辑是正确的。我遇到的问题是我不希望在我的等待函数下面的代码执行,直到得到响应。我尝试使用.then()方法进行各种变体,但均未成功。如何正确执行此操作?
截屏:
等待很好,可能只是检查查询是否提供了任何实际数据
// Search Stocks
const searchStocks = async () => {
// await data from API
const res = await axios(`https://financialmodelingprep.com/api/v3/searchquery=${state.text}&exchange=NASDAQ`);
const res2 = await axios(`https://financialmodelingprep.com/api/v3/searchquery=${state.text}&exchange=NYSE`);
// after data has returned in variables, then filter results
let filteredResults = [];
if(res1 && res2)
filteredResults = [...res, ...res2].filter(stock => stock.symbol.includes(state.text.toUpperCase()))
// dispatch to have filtered results added to state to show the user
dispatch({
type: SEARCH_STOCKS,
payload: filteredResults
});
};
编辑:我测试了它,但未在Firefox中遇到CORS策略案例,而在Chrome中,我没有这样做,您可能想查找一下,这可能是为什么axios无法返回正确数据的原因