(React Native Gesture Handler)尝试从不同线程同步调用函数

问题描述 投票:0回答:2

我正在尝试通过平移手势更改状态(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
      }
}

当我尝试从“.onEnd()”函数更新状态时,收到错误“尝试从不同线程同步调用函数”。如何正确更改手势处理程序的状态?

javascript reactjs react-native asynchronous react-native-gesture-handler
2个回答
10
投票

您的 Reanimated 组件在设备的 UI 线程上工作。其余代码将在设备的 JS 线程上运行。您的代码编写方式会尝试在 UI 线程上调用 Javascript 函数,这会导致您看到的错误。

这就是 Reanimated 包含

runOnJS
方法的原因。而不是

  setLocalShowRecents(true)

你可以使用

  runOnJS(setLocalShowRecents)(true);

注意修改后的调用签名 -

runOnJS(fn)(args)
。您可以在 Reanimated 文档中阅读有关 runOnJS 的更多信息


1
投票
这对我有用:npx react-native start --reset-cache,

https://github.com/software-mansion/react-native-reanimated/discussions/1571#discussioncomment-3108509

© www.soinside.com 2019 - 2024. All rights reserved.