异步操作后如何更新共享值?
How to update shared value after async operation?
const [action, setAction] = useState(true);
const sharedVal = useSharedValue(action ? 10 : 20)
useEffect(() => {
setTimeout(() => {
setAction(false)
}, 2000)
}, [])
在上面的代码中,shareVal
的值没有改变,action
的值改变了。在 timeout
.
之后更新 sharedVal
值的最佳方法是什么
当 action
发生变化时,您将不得不 运行 副作用。
useEffect(() => {
sharedVal.value = action ? 10 : 20;
// this will run when action is updated
}, [action]);
或者您可以随心所欲地sharedVal.value = someValue
。
(...) The reference is an object with .value
property, that can be accessed and modified from worklets, but also updated directly from the main JS thread.
试试这个方法
function Example() {
const [action, setAction] = useState(true);
React.useEffect(() => {
async function useSharedValue(number) {
const response = await fetch(....);
const json = await response.json();
setAction(true); // reset state here
}
useSharedValue(action ? 10 : 20);
}, []);
}
我有一个类似于你的代码。每次警报变量发生变化时都会调用 UseEffect,正如您在下面的代码中看到的那样。如果第二个参数为空[],useEffect只会在页面加载时执行一次。由于您想在每次操作变量的值发生变化时调用,只需将其放在 [].
中即可
useEffect(() => {
if (alert != '') setTimeout(() => { setAlert('') }, 4000);
}, [alert]);
const [action, setAction] = useState(true);
const sharedVal = useSharedValue(action ? 10 : 20)
useEffect(() => {
setTimeout(() => {
setAction(false)
}, 2000)
}, [])
在上面的代码中,shareVal
的值没有改变,action
的值改变了。在 timeout
.
sharedVal
值的最佳方法是什么
当 action
发生变化时,您将不得不 运行 副作用。
useEffect(() => {
sharedVal.value = action ? 10 : 20;
// this will run when action is updated
}, [action]);
或者您可以随心所欲地sharedVal.value = someValue
。
(...) The reference is an object with
.value
property, that can be accessed and modified from worklets, but also updated directly from the main JS thread.
试试这个方法
function Example() {
const [action, setAction] = useState(true);
React.useEffect(() => {
async function useSharedValue(number) {
const response = await fetch(....);
const json = await response.json();
setAction(true); // reset state here
}
useSharedValue(action ? 10 : 20);
}, []);
}
我有一个类似于你的代码。每次警报变量发生变化时都会调用 UseEffect,正如您在下面的代码中看到的那样。如果第二个参数为空[],useEffect只会在页面加载时执行一次。由于您想在每次操作变量的值发生变化时调用,只需将其放在 [].
中即可 useEffect(() => {
if (alert != '') setTimeout(() => { setAlert('') }, 4000);
}, [alert]);