Я пытался создать похожий значок, в котором я объявляю функцию likepress, которая должна публиковать в api каждый раз, когда пользователь нажимает на нее, а затем изменяет состояние на красное,
Это мой полный код:
import React, { Component } from 'react';
//Import React
import { AppRegistry, View, Dimensions, ActivityIndicator, FlatList, Text, TouchableOpacity, StatusBar } from 'react-native';
import { Viewport } from '@skele/components'
//Import Basic React Native Component
import Video from 'react-native-video';
import Swiper from 'react-native-swiper';
import Icon from 'react-native-vector-icons/FontAwesome';
const PRE_TRIGGER_RATIO = -0.4;
const { height } = Dimensions.get('window');
const { width } = Dimensions.get('window');
export default class Videos extends Component {
static navigationOptions = { header: null }
constructor(props) {
super(props);
this.state = {
isLoading: true,
data: [],
likeIcon: 'white',
};
}
componentDidMount() {
return fetch('some url')
.then(response => response.json())
.then(responseJson => {
this.setState(
{
isLoading: false,
data: responseJson,
},
console.log(responseJson)
);
})
.catch(error => {
console.error(error);
});
}
likePress = async() => {
if (this.state.likeIcon == 'white') {
fetch('some url' , {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
like: this.state.product._id
})
.catch(error => {
console.error(error);
})
})
.then(response => response.json())
.then(result => {
this.setState({ likeIcon: 'red', data: result })
console.log(_id,'id')
console.log(result,JSON.stringify({
like: this.state.product._id
}))
}).catch(error => {
alert(error);
console.error(error);
})
}
}
render() {
const ViewportAwareVideo = Viewport.Aware(Video);
if (this.state.isLoading) {
return (
<View style={{ flex: 1, padding: 20 }}>
<ActivityIndicator />
</View>
);
}
return (
<View >
<StatusBar hidden />
{/* <View style={{ flexDirection: 'row', justifyContent: 'flex-end', position:'absolute', zIndex:1}}> */}
<TouchableOpacity
style={{
position: 'absolute',
top:10,
left:10,
zIndex:100
}}>
<Icon
name="shopping-cart"
size={24}
style={{ paddingRight: 40}}
color="white"
/>
</TouchableOpacity>
<TouchableOpacity
style={{
position: 'absolute',
top:10,
left:40,
zIndex:100
}}
>
<Icon
name="user-circle"
size={24}
style={{ paddingRight: 20 }}
color="white"
/>
</TouchableOpacity>
{/* </View> */}
<FlatList
data={this.state.data.product}
scrollEventThrottle={1}
renderItem={({ item }) => (
<View style = {{alignContent: 'stretch'}} >
<ViewportAwareVideo
source={{ uri: item.urlVid }}
resizeMode = "cover"
preTriggerRatio={PRE_TRIGGER_RATIO}
retainOnceInViewport={false}
style={{width: width, height:height}}
innerRef={ref => this._videoRef = ref}
onViewportEnter={() => this._videoRef.play()}
onViewportLeave={() => this._videoRef.stop()}
/>
<View
style={{
position: 'absolute',
flexDirection: 'column',
alignItems: 'flex-end',
top: '50%',
right: 10,
}}>
<TouchableOpacity
onPress={this.likePress}
style={{
alignItems: 'center',
borderRadius: 60,
padding: 10,
}}>
<Icon
name="heart"
size={30}
color={this.state.likeIcon}
/>
</TouchableOpacity>
<TouchableOpacity
style={{
alignItems: 'center',
borderRadius: 60,
padding: 10,
}}>
<Icon name="share" size={30} color="white" />
</TouchableOpacity>
<Text style={{ right: 5, color: 'white' }} />
<TouchableOpacity
style={{
alignItems: 'center',
borderRadius: 60,
padding: 10,
}}>
<Icon name="whatsapp" size={30} color="white" />
</TouchableOpacity>
<Text style={{ right: 5, color: 'white' }} />
<TouchableOpacity
style={{
alignItems: 'center',
borderRadius: 60,
padding: 10,
}}>
<Icon name="download" size={30} color="white" />
</TouchableOpacity>
<Text style={{ right: 5, color: 'white' }} />
</View>
<View
style={{
position: 'absolute',
flexDirection: 'column',
top: '90%',
left: 10,
}}>
<TouchableOpacity onPress={() => this.props.navigation.navigate('Product')}>
<View
style={{
flexDirection: 'row',
}}>
<Text
style={{ fontWeight: 'bold', fontSize: 20, color: 'white' }}>
{item.title} - {item.price}
</Text>
</View>
</TouchableOpacity>
</View>
</View>
)}
keyExtractor={ item => item.id}
/>
</View>
);
}
}
Однако, при этом я могу получить основной API, но API LikePress, похоже, не работает, выдает ошибку:
Possible Unhandled Promise Rejection (id: 0):
TypeError: undefined is not an object (evaluating '_this.state.product._id')
Пожалуйста, скажите меня, где я иду не так