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

React Native问题:点击后无法将API返回的notifications.read设为true

问题分析与解决方案

你的代码里根本没对notifications.read做赋值操作,只是写了一个无意义的表达式{notifications.read == true},这就是点击后值始终不变的原因。

修复步骤:

  1. 确保notifications是可修改的组件状态
    如果notifications是从API获取后存在组件状态中的,需要用useState来管理:

    const [notifications, setNotifications] = useState(/* API返回的初始数据 */);
    
  2. 在onPress中正确更新状态
    React中状态是不可变的,不能直接修改原对象,要创建新对象来更新read属性:

    <TouchableOpacity
      onPress={() => {
        // 按需求反转read值,或直接设为true
        const updatedNotify = {
          ...notifications,
          read: !notifications.read // 若需要强制设为已读,直接写true即可
        };
        setNotifications(updatedNotify);
        console.log(updatedNotify.read); // 打印更新后的值
      }}
    >
      <Text style={{
        textDecorationLine: 'underline',
        fontSize: 14,
        color: Colors.primaryColor,
        lineHeight: 18,
        letterSpacing: 0.1,
      }}>
        标记为已读
      </Text>
    </TouchableOpacity>
    
  3. 同步更新到后端API(可选)
    如果需要把修改后的值提交回后端,在更新状态后调用API请求:

    onPress={() => {
      const updatedNotify = {
        ...notifications,
        read: true
      };
      setNotifications(updatedNotify);
      // 调用后端API更新数据
      fetch('你的API接口地址', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(updatedNotify),
      })
      .then(res => res.json())
      .then(data => console.log('后端更新成功', data))
      .catch(err => console.error('后端更新失败', err));
    }}
    

关键错误点:

  • 原代码中的{notifications.read == true}只是一个比较表达式,没有任何赋值或状态更新逻辑,完全不会改变变量的值。
  • React中不能直接修改状态对象的属性(比如notifications.read = true),必须通过状态更新函数(如setNotifications)创建新的状态对象来触发组件更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 16:48:58