简体   繁体   English

为什么 PanResponder 不能使用 useEffect Hook?

[英]Why PanResponder is not working with useEffect Hook?

I'm trying to find a replacement for ComponentWillMount method with useEffect.我正在尝试使用 useEffect 找到 ComponentWillMount 方法的替代品。 But panresponder variable is not created before the initial render.但是 panresponder 变量不是在初始渲染之前创建的。 Can anyone please tell me if any mistakes I'm doing here?谁能告诉我我在这里做的任何错误? without useEffect, the page is getting rendered.没有 useEffect,页面将被渲染。 gestures are not captured.手势未被捕获。


  
  
  
      const makeup = () => {
        useEffect(() => {
            console.log('I am about to render!');
            const panResponder = useRef(
              PanResponder.create({
                onStartShouldSetPanResponder: (e, gestureState) => true,
                onPanResponderMove: (e, gestureState) => {....},
                onPanResponderRelease: (e, gestaureState) => {....}
              }));
          },[]);

        return ARTICLES.map((item, i) => {
          console.log("Makeup i:"+i+" item:"+item);
          if (i === index.currentIndex - 1) {
            return (
              <Animated.View
                key={item.id}
                style={swipeCardPosition.getLayout()}
                {...panResponder.panHandlers}
              >
                  
              </Animated.View>
            );
          }
          if (i < index.currentIndex) {
            return null;
          }
          return (
            <Animated.View
              key={item.id}
              style={index.currentIndex === i ? position.getLayout() : null}
              {...(index.currentIndex === i
                ? { ...panResponder.panHandlers }
                : null)}
>
            </Animated.View>
          );
        }).reverse();
      };
[Error on execution][1] [1]: https://i.stack.imgur.com/sls5E.png

Check the official docs.检查官方文档。 It describes how to use PanResponder with functional components.它描述了如何将PanResponder与功能组件一起使用。

For example:例如:

const ExampleComponent = () => {
  const panResponder = React.useRef(
    PanResponder.create({
      onStartShouldSetPanResponder: (e, gestureState) => true,
      onPanResponderMove: (e, gestureState) => {....},
      onPanResponderRelease: (e, gestaureState) => {....}
    })
  ).current;

  return <View {...panResponder.panHandlers} />;
};

Your example won't work, for a large number of reasons, most notably because you can't call useRef inside useEffect .由于很多原因,您的示例将不起作用,最明显的是因为您不能在useEffect中调用useRef

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM