По сути, я делаю приложение, в котором вы проводите пальцем вправо, если хотите, и влево, если нет. Проблема, с которой я столкнулся сейчас, заключается в том, что я хочу, чтобы на карточке отображался правильный текст, который меняется в зависимости от направления, в котором пользователь проводит пальцем.
PanResponder обрабатывает изменяемый текст путем модификации state.changeText и изменяет текст в зависимости от направления. Код частично работает в настоящий момент, но проблема, с которой я столкнулся сейчас, заключается в том, что предыдущее значение состояния для changeText - это то, что отображается во время процесса считывания, а не текущее.
Код показан ниже.
import React from "react"
import {
View, Text, Animated, ScrollView, StyleSheet, Button,PanResponder,Dimensions
} from "react-native"
import Icon from "react-native-vector-icons/Ionicons"
import {Card, Badge} from "react-native-elements"
const screenWidth =Dimensions.get("window").width
const swipeThreshold = screenWidth * .25
export default class SwipeCard extends React.Component{
constructor(props){
super(props);
//this initiates the dragging animation
const position = new Animated.ValueXY();
const panResponder = PanResponder.create({
// if true anytime the user starts to click down on the screen, the panresponder handles the action
onStartShouldSetPanResponder : () => true,
//everytime the user drags on the screen
onPanResponderMove : (event, gesture) => {
//get the distance they dragged the item by and update it in the animation
position.setValue({x: gesture.dx, y: gesture.dy})
this.setState({
style:{
opacity:1,
}})
},
//everytime the user lets go
onPanResponderRelease: (event, gesture) => {
this.setState({
style:{
opacity:0,
}})
if (gesture.dx > swipeThreshold){
console.info("swipe right!");
this.setState({change: "swipe right!"})
position.setValue({x:0, y:0});
this.nextItem();
}
else if (gesture.dx < -swipeThreshold){
console.info("swipe left!");
this.changeText("swipe left")
this.setState({change: "swipe left!"})
position.setValue({x:0, y:0});
this.nextItem();
}
else{
position.setValue({x:0, y:0});
this.setState({
style:{
opacity:0,
}})
}
}
})
this.state = {
index:1,
panResponder,
position,
style:{
opacity:0,
},
changeText:"",
}
this.nextItem=this.nextItem.bind(this);
}
getCardStlye(){
const {position} = this.state;
const rotate = position.x.interpolate({
inputRange: [-screenWidth * 2, 0, screenWidth*2],
outputRange: ["-120deg", "0deg", "120deg"]
});
return {
...position.getLayout(),
transform: [{rotate}]
}
}
nextItem() {
if (this.state.index !== this.props.data.length){
this.setState({ index: this.state.index + 1 })
}
else {
this.setState({ index:0});
}
}
render(){
var cloth = this.props.data.find((cloth, i)=>{
return i+1 === this.state.index;
})
return(
<ScrollView>
{this.state.index ?(
<Animated.View
key = {cloth.deal.id}
style = {this.getCardStlye()}
{...this.state.panResponder.panHandlers}>
<Card
title = {cloth.deal.merchant.name}
image = {{uri:cloth.deal.image_url}}
>
<Text
style = {this.state.style}>
{this.state.changeText}
</Text>
<Text>${cloth.deal.price}</Text>
<Button
title = "Details"
backgroundColor = "blue"
></Button>
</Card>
</Animated.View>
)
:
<Text>Null</Text>
}
</ScrollView>
)
}
}



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


По-видимому, у вас есть ошибка, у вас нет метода изменения текста в вашем классе, но вы используете его для прокрутки влево, попробуйте удалить его и проверьте, работает ли он
if (gesture.dx > swipeThreshold){
console.info("swipe right!");
this.setState({change: "swipe right!"})
position.setValue({x:0, y:0});
this.nextItem();
}
else if (gesture.dx < -swipeThreshold){
console.info("swipe left!");
this.changeText("swipe left") // <<< HERE
this.setState({change: "swipe left!"})
position.setValue({x:0, y:0});
this.nextItem();
}
else{
Собственно я осознал свою ошибку. Добавление setState в onPanResponderMove помогло
const panResponder = PanResponder.create({
// if true anytime the user starts to click down on the screen, the panresponder handles the action
onStartShouldSetPanResponder : () => true,
//everytime the user drags on the screen
onPanResponderMove : (event, gesture) => {
//get the distance they dragged the item by and update it in the animation
position.setValue({x: gesture.dx, y: gesture.dy})
if (gesture.dx > swipeThreshold){
console.info("swipe right!");
this.setState({changeText: "swipe right!"})
}
else if (gesture.dx < -swipeThreshold){
console.info("swipe left!");
this.setState({changeText: "swipe left!"})
}
else{
this.setState({
style:{
opacity:0,
}})
}
this.setState({
style:{
opacity:1,
}
})
},
//everytime the user lets go
onPanResponderRelease: (event, gesture) => {
this.setState({
style:{
opacity:0,
}})
if (gesture.dx > swipeThreshold){
console.info("swipe right!");
this.setState({changeText: ""})
position.setValue({x:0, y:0});
this.addItems()
this.nextItem();
}
else if (gesture.dx < -swipeThreshold){
console.info("swipe left!");
this.setState({changeText: ""})
position.setValue({x:0, y:0});
this.nextItem();
}
else{
position.setValue({x:0, y:0});
this.setState({
style:{
opacity:0,
}})
}
}
})
this.state = {
index:1,
panResponder,
position,
style:{
opacity:0,
},
changeText:"",
items:[],
itemName:"",
}
Вы устанавливаете состояние с помощью this.setState ({изменение: "проведите пальцем влево!"}) И используете this.state.changeText