[英]React/Redux - When should you fetch new data from an API to update your store?
我正在嘗試使用來自API的數據更新/刷新Redux狀態時的最佳實踐。
考慮這種情況:
您有一個“待辦事項”應用程序,其中有許多用戶可能在任何給定時間點更新與您相同的“待辦事項”。 顯然,您希望本地Redux商店最終反映其他用戶的這些更改。
你會:
我現在對將更改推送到客戶端或輪詢API都不感興趣(嗯!)。 我只是想在大多數開發人員何時刷新以Redux狀態存儲的API派生數據上達成某種共識。
如果您不想推送或輪詢,則在用戶請求時獲取數據。 從不獲取可能非常適合邊緣案例應用程序,但絕對不是常見的使用案例。
這是我從你的問題中得到的
我現在對將更改推送到客戶端或輪詢API都不感興趣(嗯!)。
我不明白這是干什么的。 您可能未在更新應用程序,但要查看您的應用程序應由一個或其他更新的更改。
除此之外,我還告訴您在任何獲取數據的地方都訂閱數據的獲取。 我不知道您對訂閱的理解,根據我的說法,訂閱是為了定期進行獲取以獲取更新。 訂閱本質上是異步的。
我給出一個實現訂閱的簡單示例。
console.log("Started");
let subscription = false;
const getData = () => {
// call your database and fetch the data and once
// fetching done call the getData again
// Think setTimeout as database call.
// upon resolving the data I called it again
// It neither stops other call back from running run
setTimeout(() => {
console.log("Fetching");
if(subscription) {
console.log("shuting");
return;
}
getData();
}, 1000);
}
getData();
setTimeout(() => {
console.log("hello");
}, 5000);
setTimeout(() => {
subscription = true;
}, 8000);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.