You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native点赞按钮点击计数功能实现求助

解决React Native点赞按钮不更新计数的问题

看起来你的点赞功能有几个关键问题导致计数无法正常更新,我帮你梳理并修复一下:

问题分析

  • 初始状态与API数据不同步:你初始化count为0,但从API获取的data本身带有count值,这会导致初始显示的计数和实际数据不一致,点击更新时也会基于错误的初始值计算。
  • 更新逻辑错误:update方法里用this.state.data.count + 1来更新,但data是从API获取后就不会主动变化的(除非重新请求),所以每次点击都会用同一个初始的data.count值加1,而不是基于当前已更新的计数。
  • 显示的计数来源错误:你在界面上显示的是this.state.data.count,但实际点击后更新的是this.state.count,所以界面不会同步变化。
  • JSX语法不完整:你的render方法返回的JSX没有闭合所有标签,这会直接导致渲染错误。

修复后的完整代码

import React from 'react';
import { StyleSheet, View, Image, TouchableOpacity, Text, StatusBar, ScrollView } from 'react-native';

export default class SingleVeg extends React.Component {
  constructor(props) {
    super(props);
    console.log("Here", props);
    // 初始count设为null,后续从API数据同步
    this.state = { data: {}, count: null };
    this.update = this.update.bind(this);
  }

  update() {
    // 使用函数式setState确保获取最新的state值,避免异步更新导致的错误
    this.setState(prevState => ({
      count: prevState.count + 1
    }));
  }

  async componentDidMount() {
    const response = await fetch(`https://just-ripe.herokuapp.com/vegetable/${this.props.navigation.state.params.id}`);
    const json = await response.json();
    // 同步API返回的count到state.count,确保初始计数和后端一致
    this.setState({ data: json, count: json.count });
  }

  render() {
    console.log(typeof this.state.data, this.state.data.id);
    // 处理count还未加载的情况,避免显示undefined
    const currentCount = this.state.count ?? 0;
    
    return (
      <View style={styles.container}>
        <StatusBar />
        <ScrollView>
          <View style={styles.image}>
            <Image style={{ width: 350, height: 200 }} source={require("../../images/JustRipe.png")} />
          </View>
          <Text style={styles.title}>{this.state.data.title}</Text>
          <TouchableOpacity style={styles.love} onPress={this.update}>
            <Text style={styles.loveText}>Love: {currentCount}</Text>
          </TouchableOpacity>
        </ScrollView>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    paddingTop: 20,
  },
  image: {
    marginBottom: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 15,
  },
  love: {
    padding: 10,
    backgroundColor: '#ffcccc',
    borderRadius: 5,
  },
  loveText: {
    fontSize: 18,
  },
});

关键修改点说明

  1. 同步API数据到state.count:在componentDidMount获取数据后,把json.count赋值给state.count,确保初始计数和后端数据一致。
  2. 函数式setState更新计数:使用prevState来获取最新的计数状态,避免因React状态更新的异步性导致的错误计算。
  3. 显示state.count而非data.count:界面上显示currentCount(即state.count),确保点击后界面能同步更新。
  4. 处理未加载状态:用this.state.count ?? 0处理API还未返回数据时的情况,避免显示undefined。
  5. 补全JSX标签:修复了render方法里未闭合的ScrollView和View标签,确保组件能正常渲染。

如果需要把点赞数据同步回后端,你还可以在update方法里添加提交请求,示例如下:

async update() {
  const newCount = this.state.count + 1;
  // 先更新本地状态,保证界面及时反馈
  this.setState({ count: newCount });
  // 再同步到后端
  try {
    await fetch(`https://just-ripe.herokuapp.com/vegetable/${this.props.navigation.state.params.id}`, {
      method: 'PUT', // 假设后端用PUT接口更新数据
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ count: newCount }),
    });
  } catch (error) {
    console.error('更新点赞数失败:', error);
    // 如果后端更新失败,回滚本地状态
    this.setState(prevState => ({ count: prevState.count - 1 }));
  }
}

内容的提问来源于stack exchange,提问作者Makayla Clausen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:41:43