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

React Native+Firebase:TextInput数字存入Firestore数组格式异常求助

问题排查与修复方案

你的问题出在没有对用户输入的逗号分隔字符串做拆分和类型转换,直接把整个字符串作为数组的单个元素存入Firestore了,所以得到的是["5, 4 ,5, 3, 5"]这种格式,而非预期的数字数组[5,4,5,3,5]。

修复步骤

  • 对输入的字符串按逗号分割,去除每个元素的前后空格
  • 过滤掉分割后可能出现的空字符串(比如用户输入连续逗号的情况)
  • 将每个字符串元素转换为数字类型
  • 用处理后的数字数组更新Firestore

修改后的代码

const [numberInput, setNumberInput] = useState("") // 初始值设为空字符串更合理

// Sending a value.
const EditSubject = () => {
    const addSub = doc(db, 'users', userUID, 'evaluations', 'SecondCours', 'FirstSemestr', 'FirstSemestr');
    // 检查输入是否有效
    if (numberInput?.trim()) {
        // 处理输入字符串为数字数组
        const numberArray = numberInput
            .split(',') // 按逗号分割
            .map(item => item.trim()) // 去除每个元素的空格
            .filter(item => item) // 过滤空元素
            .map(item => Number(item)); // 转换为数字
        
        updateDoc(addSub, {Mathematics: numberArray});
        setModalWindow(false)
    } else {
        setModalWindow(false)
    }
}

// Getting the value.
<TextInput 
    style={[{backgroundColor: theme.colors.addSubjectText, color: theme.colors.text1}, styles.TInput]} 
    keyboardType='numeric' 
    onChangeText={num => setNumberInput(num)}
/>

额外说明

  • 原代码里的textInput是笔误,已修正为对应state变量numberInput
  • 给useState设置初始空字符串,避免未输入时出现undefined的问题
  • 增加trim()检查输入是否为空,避免无效提交

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 02:20:34