从Firestore获取数据时空字段显示undefined 如何设置为展示空白内容
问题原因
JavaScript 中undefined和字符串拼接时会被自动转为字符串"undefined",你当前直接拼接字段的写法,只要某一个字段在Firestore中无值(返回undefined),就会出现异常的undefined文本。
修复方案
方案1:空值兜底(最简写法)
用空值合并运算符??给每个字段设置默认空字符串,只要字段值为undefined/null就会自动替换为空:
componentDidMount() { firestore .collection("users") .get() .then((snapshot) => { const users = []; snapshot.forEach((doc) => { const data = doc.data(); users.push({ "User ID": doc.id, Address: `${data.address ?? ""}, ${data.city ?? ""}, ${data.province ?? ""}` }); }); this.setState({ users }); }) .catch((error) => console.log(error)); }
提示:你原代码里省份字段拼写为provice,建议核对是否和Firestore中存储的字段名一致,拼写错误也会导致取到undefined值
方案2:过滤空值后拼接(优化展示效果)
方案1如果存在空字段,会出现多余逗号(比如上海市, , 静安区),如果需要避免这个问题,可以先把地址字段放到数组中过滤掉空值,再拼接:
componentDidMount() { firestore .collection("users") .get() .then((snapshot) => { const users = []; snapshot.forEach((doc) => { const data = doc.data(); // 过滤掉undefined、null、空字符串等无效值 const addressParts = [data.address, data.city, data.province].filter(Boolean); users.push({ "User ID": doc.id, Address: addressParts.join(", ") }); }); this.setState({ users }); }) .catch((error) => console.log(error)); }
内容的提问来源于stack exchange,提问作者JS3
相关产品推荐
相关产品推荐

