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
相关产品推荐
相关产品推荐

