Eth*_*cey 4 javascript asynchronous reactjs react-native react-native-gesture-handler
我正在尝试从平移手势(React Native Gesture Handler)更改状态。
const [localShowRecents, setLocalShowRecents] = useState(false)
const translateY = useSharedValue(0);
const gesture = Gesture.Pan()
.onStart(() => {
context.value = { y: translateY.value }
})
.onUpdate((event) => {
//console.log(event.translationY);
translateY.value = event.translationY + context.value.y;
translateY.value = Math.max(translateY.value, MAX_TRANSLATE_Y)
})
.onEnd(() => {
if (translateY.value > -SCREEN_HEIGHT / 32){
setLocalShowRecents(true); //change state
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试从“.onEnd()”函数更新状态时,收到错误“尝试从不同线程同步调用函数”。如何正确更改手势处理程序的状态?
您的 Reanimated 组件在设备的 UI 线程上工作。其余代码将在设备的 JS 线程上运行。您的代码编写方式会尝试在 UI 线程上调用 Javascript 函数,这会导致您看到的错误。
这就是 Reanimated 包含该runOnJS方法的原因。代替
setLocalShowRecents(true)
Run Code Online (Sandbox Code Playgroud)
您可以使用
runOnJS(setLocalShowRecents)(true);
Run Code Online (Sandbox Code Playgroud)
请注意修改后的调用签名 - runOnJS(fn)(args)。您可以在 Reanimated 文档中阅读有关 runOnJS 的更多信息。
| 归档时间: |
|
| 查看次数: |
1925 次 |
| 最近记录: |