【问题标题】:Fetch api when like button is clicked单击“赞”按钮时获取 api
【发布时间】:2020-05-15 16:38:14
【问题描述】:

我使用 react native 在前端创建了一个类似的图标,我希望它在点击类似图标后立即发布到 api,因此我创建了一个单独的 likePress() 函数,其中包含一个 if声明,其中只有在单击时它的颜色才会变为红色并应该返回 spi,但是作为新手会错过一些东西。

以下是我的likePress()函数的sn-p:

     likePress = async() => {
    if (this.state.likeIcon == 'white') {
      this.setState({ likeIcon: 'red' }); 
    }    
    if (this.state.likeIcon == 'red') {
        fetch('some url' +product._id, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                like: this.state.product._id
            })

        })
        .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);
        })
    }
}

并在平面列表中的以下内容中调用此函数:

<TouchableOpacity
                onPress={this.likePress}
                style={{
                  alignItems: 'center',

                  borderRadius: 60,
                  padding: 10,
                }}>
                <Icon
                  name="heart"
                  size={30}
                  color={this.state.likeIcon}

                />
              </TouchableOpacity>

请帮助我了解这样做是否正确。 请告诉我,如果还有其他需要,谢谢。

我的日志,现在:

 {"product": [{"__v": 0, "_id": "5e301696f75182463c6874ed", "color": "Space Grey", "colors": [Array], "description": "6.5-inch Super Retina XDR OLED display
Water and dust resistant (4 meters for up to 30 minutes, IP68)
Triple-camera system with 12MP Ultra Wide, Wide, and Telephoto cameras; Night mode, Portrait mode, and 4K video up to 60fps
12MP TrueDepth front camera with Portrait Mode, 4K video, and Slo-Mo
Face ID for secure authentication and Apple Pay
A13 Bionic chip with third-generation Neural Engine
Fast charge with 18W adapter included
Wireless charging
Manufacturer Detail: Apple Inc, One Apple Park Way, Cupertino, CA 95014, USA", "downloads": 2, "nameImg": "61jgfLBydjL._SL1024_-1580209807807.jpg", "nameVid": "videoplayback (1)-1580209807809.mp4", "price": 99900, "sellerID": "13755902031", "sellerName": "Appario", "size": "5.8-inch", "sizes": [Array], "title": "Apple iPhone 11 Pro", "typeImg": "image/jpeg", "typeVid": "video/mp4", "uploadedOn": "2020-01-28T11:10:14.244Z", "urlImg": "https://atiiproductmediafiles.s3.ap-south-1.amazonaws.com/61jgfLBydjL._SL1024_-1580209807807.jpg", "urlVid": "https://atiiproductmediafiles.s3.ap-south-1.amazonaws.com/videoplayback+%281%29-1580209807809.mp4"}, {"__v": 0, "_id": "5e30171df75182463c6874ee", "color": "Haze Blue", "colors": [Array], "description": "Rear Camera - 48MP (Primary) + 8MP (Tele-photo)+16MP (Ultrawide) | Front Camera - 16 MP POP-UP Camera
16.9 centimeters (6.67-inch) multi-touch capacitive touchscreen with 3120 x 1440 pixels resolution
Memory, Storage and SIM: 6GB RAM | 128GB internal memory | Dual SIM dual-standby (4G+4G)
Android Oxygen operating system with 2.84GHz Snapdragon 855 octa core processor
4000mAH lithium-ion battery
1 year manufacturer warranty for device and 6 months manufacturer warranty for in-box accessories including batteries from the date of purchase
Box also includes: Power Adapter, Type-C Cable (Support USB 2.0), Quick Start Guide, Welcome Letter, Safety Information and Warranty Card, Logo Sticker, Case, Screen Protector (pre-applied) and SIM Tray Ejector", "downloads": 1, "nameImg": "61FRLa8IFTL._SL1500_-1580209943294.jpg", "nameVid": "videoplayback-1580209943295.mp4", "price": 53999, "sellerID": "13755902031", "sellerName": "OnePlus", "size": "6.67 inch", "sizes": [Array], "title": "OnePlus 7T Pro", "typeImg": "image/jpeg", "typeVid": "video/mp4", "uploadedOn": "2020-01-28T11:12:29.918Z", "urlImg": "https://atiiproductmediafiles.s3.ap-south-1.amazonaws.com/61FRLa8IFTL._SL1500_-1580209943294.jpg", "urlVid": "https://atiiproductmediafiles.s3.ap-south-1.amazonaws.com/videoplayback-1580209943295.mp4"}, {"__v": 0, "_id": "5e3273ae32213d4ba037042a", "color": "assas", "colors": [Array], "description": "assa", "downloads": 0, "nameImg": "apex-legends-logo-1580364717181.jpg", "nameVid": "videoplayback (2)-1580364717241.mp4", "price": 222, "sellerID": "sas", "sellerName": "sasa", "size": "sdassa", "sizes": [Array], "title": "wws", "typeImg": "image/jpeg", "typeVid": "video/mp4", "uploadedOn": "2020-01-30T06:11:58.768Z", "urlImg": "https://atiiproductmediafiles.s3.ap-south-1.amazonaws.com/apex-legends-logo-1580364717181.jpg", "urlVid": "https://atiiproductmediafiles.s3.ap-south-1.amazonaws.com/videoplayback%20%282%29-1580364717241.mp4"}], "user": {"__v": 0, "_id": "5e300846241a3b1c89d654c4", "address": [], "changes": [], "checkout": [], "like": [], "mobile": 8697779335, "orders": [], "registeredOn": "2020-01-28T10:09:10.569Z"}}

如您所见,它没有传递产品 ID,而只是获取我用来在平面列表中查看视频的第一个 api。

【问题讨论】:

  • 您遇到的错误是什么?
  • onPress={this.likePress()} => onPress={this.likePress}
  • fetch 返回一个承诺,所以我看不到您在任何地方使用响应数据。这是我可以看到的一件不好的事情。 Tim 指出您需要参考,但您正在执行它。
  • 我已经做出了更改,并添加了一个承诺,即 fetch 应该按照您的建议返回并按照@Tim 进行更改,您现在可以说这是否足够或者我错过了什么?
  • @TRINACHAUDHURI 我仍然可以看到onPress={this.likePress()}。更改它并查看其他是否正确,但首先检查 likeIcon 似乎没有必要。意思是如果图标是白色的,那么为什么将其设置为白色。

标签: reactjs react-native react-native-android react-native-flatlist react-native-navigation


【解决方案1】:

当您通过this.setState({ likeIcon: "red" })将likeIcon设置为红色时,您无法在setState之后直接检查状态是否设置为红色,因为它是异步的(链接到doc)。

您可以使用下面提供的布尔值isRed 替换该逻辑,只有在按下按钮之前likeIcon 的状态为白色时才会调用API。

likePress = async () => {
        let isRed = false;
        if (this.state.likeIcon === "white") {
            this.setState({ likeIcon: "red" });
            isRed = true;
        }
        if (isRed) {
            try {
                const response = await fetch("some url" + product._id, {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({ like: this.state.product._id })
                });
                const json = await response.json();
                this.setState({
                    likeIcon: "red",
                    data: json
                });
                console.log(_id, "id");
                console.log(
                    result,
                    JSON.stringify({
                        like: this.state.product._id
                    })
                );
            } catch (error) {
                console.error(error);
            }
        }
    };

我还对其进行了更改,以便您使用 async await 而不是回调函数,在我看来这会使 onPress 更易于阅读。

【讨论】:

    【解决方案2】:

    你应该如下修改函数。

    likePress = () => {
        if (this.state.likeIcon != 'white') {
            fetch('some url', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    like: this.state.product._id
                })
            }).then(result => {
                this.setState({ likeIcon: 'red' })
            }).catch(error => {
                //do something with error
            })
        }
    }
    

    这将在响应获取成功时更新状态。

    【讨论】:

    • 嗨,我已经更新了我的功能,请检查并告诉我是否还有什么遗漏
    • 你有什么错误和_id的值将是未定义的'console.log(_id,'id')。如果您遇到任何错误,也可以发布错误。@Trina Chaudhuri
    • 不,我没有收到任何错误,API 也没有被获取或响应,甚至日志也没有显示任何内容
    • 我做了更多的更改,但它没有获取api,请帮助,我什至会发布日志
    • 你能用邮递员检查 url 并检查它是否在邮递员@TRINA CHAUDHURI 上工作
    猜你喜欢
    • 2011-07-22
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多