开发者问题收集

当点赞图标为红色时,发布到 api

2020-01-30
110

我一直在尝试创建一个点赞图标,在其中声明一个 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,但 likepress api 似乎不起作用,它向我抛出一个错误:

Possible Unhandled Promise Rejection (id: 0):
TypeError: undefined is not an object (evaluating '_this.state.product._id')

请告诉我哪里出错了

2个回答

您尚未定义或初始化product._id,您必须为product._id设置值,因为它正在尝试读取值。

请在构造函数中添加如下内容:

constructor(props) {
    super(props);
    this.state = {
        isLoading: true,
        data: [],
        likeIcon: 'white',
        product:{_id:null}

    };

  }
Niraj
2020-01-30

我犯了一个严重的错误,没有调用 JSON 中产品数组内的准确 id,当我同样调用时,它就为我工作了,现在将在工作模块下方发布:

onButtonPress = async() => {
    if (this.state.buttonColor == "white") {
     fetch("some url",{
       method:"POST",
       headers:{
        "Content-Type": "application/json",
       },
       body:JSON.stringify({
         "args":{
           "product":[
             "_id"
           ],
           "limit":1
         }
       })
     })
     .then((res)=>res.text())
     .then((responseJson)=>{
       this.setState({buttonColor : "red"});
     })
     .catch((error)=>{
      console.error(error);
    });
    }
  };

感谢您的所有帮助,很高兴得到帮助并纠正我的错误。

TRINA CHAUDHURI
2020-01-30