[英]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.我在做什么:更改 state 以响应用户的向上/向下滑动。 Environment: React native 0.61.5
环境:反应原生 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,基本上我想增加/减少 onMoveShouldSetPanResponder 内的 state 参数,
Now, On First fire of onMoveShouldSetPanResponder, 'abc' is incremented/decremented successfully.现在,在 onMoveShouldSetPanResponder 第一次触发时,'abc' 已成功递增/递减。 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).然而,在那之后在所有连续的火灾中,onMoveShouldSetPanResponder function 内的控制台总是将 abc 打印为0 (即初始值)。 It never changes.
它永远不会改变。
Is it that we cannot access updated state inside onMoveShouldSetPanResponder?是不是我们无法在 onMoveShouldSetPanResponder 中访问更新的 state? 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);
abc 变量是一个陈旧的闭包,您可以将回调传递给 state 设置器:
setabc(currentValue=>currentValue + 1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.