简体   繁体   中英

Cannot access updated state or props inside onPanResponderMove

What am I Trying to do: To change the state in response to user's up/down swipe. Environment: React native 0.61.5

I have the component as follows.

import React, { useRef, useState } from 'react';
import { View, PanResponder } from 'react-native';

function SimpleWrapper(props) {
  const { children } = props;

  const [abc, setabc] = useState(0);

  console.log('SimpleWrapper', abc);

  const panResponder = useRef(
    PanResponder.create({
      onStartShouldSetPanResponder: (evt, gestureState) => handleShouldSetPanResponder(evt, gestureState),
      // onStartShouldSetPanResponderCapture: (evt, gestureState) => handleShouldSetPanResponder(evt, gestureState),
      onMoveShouldSetPanResponder: (evt, gestureState) => handleShouldSetPanResponder(evt, gestureState),
      // onMoveShouldSetPanResponderCapture: (evt, gestureState) => handleShouldSetPanResponder(evt, gestureState),
      // onPanResponderGrant: (evt, gestureState) => console.log('onPanResponderGrant', gestureState),
      onPanResponderMove: (evt, gestureState) => handleonPanResponderMove(evt, gestureState),
      onPanResponderTerminationRequest: () => {}
      // onPanResponderRelease: (evt, gestureState) => handlePanResponderRelease(evt, gestureState)
    })
  ).current;

  const handleShouldSetPanResponder = (evt, gestureState) => {
    const { dy } = gestureState;
    const isvalid = evt.nativeEvent.touches.length === 1 && Math.abs(dy) > gestureConfig.gestureIsClickThreshold;
    return isvalid;
  };

  const handleonPanResponderMove = (evt, gestureState) => {
    const { dy, vy } = gestureState;
    console.log('in handleonPanResponderMove:', abc, gestureState);
    if (dy < 0) {
      setabc(abc + 1);
    } else if (dy > 0) {
      setabc(abc - 1);
    }
    // }
  };

  return (
    <View {...panResponder.panHandlers} style={}>
      {children}
    </View>
  );
}

export default SimpleWrapper;

Basically i want to increment/decrement the state parameter inside onMoveShouldSetPanResponder,

Now, On First fire of onMoveShouldSetPanResponder, 'abc' is incremented/decremented successfully. The topmost console in the component also shows new value.

However, After that in all consecutive fires, the console inside the onMoveShouldSetPanResponder function always prints abc as 0 (ie the initial value). It never changes.

Is it that we cannot access updated state inside onMoveShouldSetPanResponder? Am i missing something or is there another way to do this?

The abc variable is a stale closure you can pass a callback to a state setter: setabc(currentValue=>currentValue + 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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