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

React Native中基于状态实现多用户ID的关注/取消关注组件

修复React Native关注/取消关注按钮状态异常问题

原代码核心问题

  1. 关注状态判断逻辑错误:user.user_id !== ids是拿单个用户ID和整个ID数组比较,永远返回true,导致按钮状态判断完全失效
  2. 重复弹出alert:alert放在组件函数顶层,每次组件渲染(包括状态更新后)都会触发,严重影响体验
  3. 使用index作为key:列表项key不稳定,当列表顺序变化时可能引发不必要的组件重渲染或状态混乱
  4. 关注对象结构不一致:添加关注时只传入了id和username,缺少初始状态中的user_id字段,可能导致后续逻辑异常

修正后的完整代码

import React, { useState } from 'react'
import { Pressable, Text, View } from 'react-native'

const users = [
  { id: 1, user_id: 1, username: 'Jerry' },
  { id: 2, user_id: 2, username: 'Peter' },
  { id: 3, user_id: 3, username: 'Sumo' },
  { id: 4, user_id: 4, username: 'Musu' }
]

export default function TestingScreen() {
  const initialState = [
    { id: 1, user_id: 1, username: 'Jerry' }
  ]

  const [followingList, setFollowingList] = useState(initialState);
  // 提取关注列表中的用户ID数组,用于快速判断
  const followingIds = followingList.map(item => item.id);

  return (
    <View style={{
      backgroundColor: 'white',
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center'
    }}>
      {users.map((user) => (
        <View key={user.id} style={{ marginVertical: 10 }}>
          <Text style={{ fontSize: 20 }}>{user.id}</Text>
          <Text style={{ fontSize: 20 }}>{user.username}</Text>

          {!followingIds.includes(user.id) ? (
            <Pressable
              style={{ fontSize: 20, backgroundColor: 'black', padding: 10, marginTop: 5 }}
              onPress={() => {
                // 使用函数式更新获取最新状态,添加完整的用户对象
                setFollowingList(prev => [...prev, user]);
              }}
            >
              <Text style={{ fontSize: 20, color: 'white' }}>Follow</Text>
            </Pressable>
          ) : (
            <Pressable
              style={{ fontSize: 20, backgroundColor: '#eee', padding: 10, marginTop: 5 }}
              onPress={() => {
                // 过滤掉当前用户,更新关注列表
                setFollowingList(prev => prev.filter(item => item.id !== user.id));
              }}
            >
              <Text style={{ fontSize: 20, color: 'black' }}>Unfollow</Text>
            </Pressable>
          )}
        </View>
      ))}
    </View>
  )
}

关键修改说明

  • 修正状态判断逻辑:用followingIds.includes(user.id)准确判断当前用户是否已被关注,替代原有的错误比较方式
  • 移除冗余alert:去掉组件顶层的alert,避免频繁弹窗干扰操作
  • 替换稳定key:将列表项的key从index改为user.id,保证每个列表项的key唯一且稳定,避免渲染异常
  • 保持对象结构一致:关注时直接传入完整的user对象,确保关注列表中的数据结构统一
  • 优化状态更新:使用函数式更新(prev => ...)获取最新的状态值,避免因状态异步更新导致的逻辑错误
  • 添加基础样式优化:给按钮添加marginTop,给列表项添加marginVertical,提升界面可读性

内容的提问来源于stack exchange,提问作者Kelvin Nimely

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 14:40:36