[英]Use fetch results to make another fetch request (JS/React)
使用一個獲取請求的結果向另一個端點發出另一個獲取請求的最佳方法是什么? 如何確認第一次獲取已完成且setState已發生?
class ProductAvailability extends React.Component {
state = {
store_ids: []
}
componentDidMount() {
fetch(`myapi.com/availability?productid=12345`)
.then((results) => {
return results.json();
})
.then((data) => {
const store_ids = data.result.map((store) => {
return store.store_id
})
this.setState({store_ids: store_ids})
})
/* At this point I would like to make another request
to myapi.com/storedata endpoint to obtain information
on each store in the state.store_ids, and add details
to the state */
}
render() {
return (
<div>
<p>STORE INFO FROM STATE GOES HERE</p>
</div>
)
}
}
當您執行setState時,它將更新組件,因此,如果您已經閱讀了文檔,則在完成setstate之后自然要讀取狀態的點位於componentDidUpdate(prevProps,prevState)中。 我將您留給文檔: https ://reactjs.org/docs/react-component.html#componentdidupdate注意:不要使用willupdate,因為在文檔中閱讀它是不安全的。
可以做進一步的考慮。 如果可以避免將這些數據置於狀態,則還可以在componendDidMount中進行所有操作(可能對所有其他請求使用promiseall),然后使用新舊數據設置狀態,這是可取的,因為更新了組件只有一次。
使用async/await
更加容易( .then/.catch
需要做更多的工作-同樣,請參考Bluebird的Promise.each函數)。 為了清楚起見,最好將其從componentDidMount
移到其自己的類方法中。
附帶說明一下,如果每個產品都在執行此操作,則該二級查詢應在后端處理。 這樣,您只需要發出一個 AJAX
請求並在一個響應中檢索所需的所有內容。
componentDidMount = () => this.fetchData();
fetchData = async () => {
try {
const productRes = fetch(`myapi.com/availability?productid=12345`) // get product data
const productData = await productRes.json(); // convert productRes to JSON
const storeIDs = productData.map(({store_id}) => (store_id)); // map over productData JSON for "store_ids" and store them into storeIDs
const storeData = [];
await Promise.each(storeIDs, async id => { // loop over "store_ids" inside storeIDs
try {
const storeRes = await fetch(`myapi.com/store?id=${id}`); // fetch data by "id"
const storeJSON = await storeRes.json(); // convert storeRes to JSON
storeData.push(storeJSON); // push storeJSON into the storeData array, then loop back to the top until all ids have been fetched
} catch(err) { console.error(err) }
});
this.setState({ productData, storeData }) // set both results to state
} catch (err) {
console.error(err);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.