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

React Native 实现FlatList新增考试项时对比前项分数触发Alert功能

实现方案

你只需要修改addExam方法,增加分数对比逻辑即可,修改后的代码如下:

const addExam = (subject) => {
  if (termInput === '' || markInput === '' || gradeInput === ''){
    Alert.alert('Error', 'Please fill in all box');
  } else {
    const newExam = {
      id: Math.random().toString(),
      Term: termInput,
      Mark: markInput,
      Grade: gradeInput,
    };
    // 新增分数对比逻辑
    if (exam.length > 0) {
      // 转换为数字比较,避免字符串比较的问题
      const lastMark = Number(exam[exam.length - 1].Mark);
      const currentMark = Number(markInput);
      if (currentMark < lastMark) {
        Alert.alert('提示', '你本次的分数低于上一次考试');
      }
    }
    setExam([...exam,newExam]);
    setTermInput('');
    setMarkInput('');
    setGradeInput('');
  }
};

改动说明

  • 只有当已有考试条目时才会触发分数对比,第一条考试不会弹出提示
  • 输入的分数和存储的分数默认是字符串格式,统一转为Number类型再做数值比较,避免出现逻辑错误
  • 取数组最后一条考试记录作为上一次考试的对比基准,符合你给出的使用场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 09:42:02