gpt4 book ai didi

react-native - React Native panResponder 具有来自 useState 的陈旧值(value)?

转载 作者:行者123 更新时间:2023-12-03 18:33:58 25 4
gpt4 key购买 nike

我需要读取 useStateonPanResponderMove 的值。在页面加载 onPanResponderMove 正确记录了 0 的初始值。

但是,在我单击 TouchableOpacity 以增加 foo 后, onPanResponderMove 仍然会注销 0 而不是它的新值。

export default function App() {
const [foo, setFoo] = React.useState(0);

const panResponder = React.useRef(
PanResponder.create({
onStartShouldSetPanResponder: (evt, gestureState) => true,
onStartShouldSetPanResponderCapture: (evt, gestureState) => true,
onMoveShouldSetPanResponder: (evt, gestureState) => true,
onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,
onPanResponderGrant: (evt, gestureState) => {},
onPanResponderMove: (evt, gestureState) => {
console.log(foo); // This is always 0
},
onPanResponderTerminationRequest: (evt, gestureState) => true,
onPanResponderRelease: (evt, gestureState) => {},
onPanResponderTerminate: (evt, gestureState) => {},
onShouldBlockNativeResponder: (evt, gestureState) => {
return true;
},
})
).current;

return (
<View style={{ paddingTop: 200 }}>
<TouchableOpacity onPress={() => setFoo(foo + 1)}>
<Text>Foo = {foo}</Text>
</TouchableOpacity>
<View
{...panResponder.panHandlers}
style={{ marginTop: 200, backgroundColor: "grey", padding: 100 }}
>
<Text>Text for pan responder</Text>
</View>
</View>
);
}

最佳答案

平移响应器取决于值“foo”。 useRef 在这里不是一个好的选择。你应该用 useMemo 替换它

const panResponder = useMemo(
() => PanResponder.create({
[...]
onPanResponderMove: (evt, gestureState) => {
console.log(foo); // This is now updated
},
[...]
}),
[foo] // dependency list
);

关于react-native - React Native panResponder 具有来自 useState 的陈旧值(value)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61014169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com