![](/img/trans.png)
[英]How to share state between reducers in react (using hooks) without redux
[英]Share mutable state between multiple invocations of a React component with hooks
我想創建一個withPromise
,它的工作方式如下:
import {useState, withEffect} from "react";
function usePromise(promise, default=null) {
// This state variable will hold the value of our promise.
// We allow the user to pass in a default value that'l be returned
// as long as the promise hasn't been resolved.
let value, setValue = useState(default);
// Ensure that this is only re-run when the promise changes.
withEffect(() => {
promise.then(setValue)
}, [promise])
return value;
}
如果promise參數永不更改,則此方法效果很好,但是我希望它能夠適應新的promise傳入的情況,因為在這一點上,它可能會導致競爭狀態。
promise1
傳遞給usePromise
promise2
傳遞給usePromis-e
promise2
已解析,將值設置為value2
promise1
已解析,將值設置為value1
在此事件序列中,新承諾的價值將被舊承諾的價值覆蓋,並在以后解決。
但是由於不能取消承諾,因此我看不到一種方法來檢查承諾的回調,在等待解決時是否傳遞了新的承諾。
有什么辦法可以做到嗎?
useEffect可以返回用於拆卸邏輯的函數。 雖然您無法取消承諾,但是可以設置一個標志,然后檢查該標志何時解析為中止回調。 例如,如下所示:
function usePromise(promise, default=null) {
let [value, setValue] = useState(default);
useEffect(() => {
let cancelled = false;
promise.then((result) => {
if (!cancelled) {
setValue(result);
}
})
return () => cancelled = true;
}, [promise])
return value;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.