【发布时间】:2021-07-17 19:24:42
【问题描述】:
我在 useEffect 中使用了两个 API。一个是用于参数以及何时返回结果。我正在根据第一个 API 收到的参数数据数组获取主 API,然后无论我从主 API 获得的最终数据如何,我都将其设置为称为股票的状态。
问题是状态没有快速更新,它需要大约 10 秒的时间来更新,因此我无法渲染结果。我已经使用反应开发工具检查了一段时间后状态正在更新,并且我成功地从 API 获得了结果。
这里是代码。
const Base = (props) => {
const [stocks,setStocks] = useState();
useEffect(()=>{
const array = [];
axios.get(`https://pkgstore.datahub.io/core/nyse-other-listings/nyse-listed_json/data/e8ad01974d4110e790b227dc1541b193/nyse-listed_json.json`)
.then(response => {
response.data.slice(0,20).map(item =>{
axios.get(`https://finnhub.io/api/v1/stock/metricsymbol=${item["ACT Symbol"]}&metric=all&token=process.env.REACT_APP_TOKEN`)
.then((response) =>{
array.push(response)})
})
})
.catch(err => console.error(err))
setStocks(array)
},[])
return (
<div>
<div className="table_container">
<table class="table">
<thead>
<tr>
<th scope="col">COMPANY NAME</th>
<th scope="col">SYMBOL</th>
<th scope="col">MARKET CAP</th>
<th scope="col"> </th>
<th scope="col">CURRENT PRICE</th>
</tr>
</thead>
<tbody>
{
stocks !== undefined && stocks.length > 0?
stocks && stocks.map(item=>{
return <p>{JSON.stringify()}</p> //here i am getting empty []
})
:<h1>{JSON.stringify(stocks)}</h1>
}
</tbody>
</table>
</div>
</div>
)
}
导出默认基础;
【问题讨论】:
-
您似乎正在拨打两个网络电话,一个接一个。根据这些服务的速度,您最终会遇到延迟。
-
setStocks(array)将永远是setStocks([])。 然后您将获得异步调用的结果,然后您将获得 20 次辅助异步调用的结果,前提是服务器不会阻止您进行 DDoS 攻击。调用将一无所获,因为在等待 Axios 之前已经调用了setStocks([])。此外,您正在使用.map而不从中返回任何内容
标签: javascript reactjs async-await use-effect use-state