这是我的代码:
export const newPost = functions.firestore
.document('post/{postId}/')
.onCreate((snap, context) => {
const postData = snap.data()
const authorId = postData.uid
});
我收到 postData 可能未定义的错误,解决此问题的方法是检查 postData != null ,然后在 {} 内使用 postData 对象。
这是文档中的代码:
exports.createUser = functions.firestore
.document('users/{userId}')
.onCreate((snap, context) => {
// Get an object representing the document
// e.g. {'name': 'Marie', 'age': 66}
const newValue = snap.data();
// access a particular field as you would any JS property
const name = newValue.name;
// perform desired operations ...
});
这里没有提到可能存在未定义的对象newValue,而且通过阅读许多带有firestore的云函数示例我还没有看到人们在使用它之前会检查是否.data() != null
您的 TypeScript 配置几乎肯定启用了严格的类型检查,当您尝试访问可能为 null 或未定义的属性时,这会向您发出此警告。检查你的 tsconfig.json 并查找"strict": true"
在编译器选项中。 TypeScript 绑定DataSnapshot.data()API 表示 data() 的返回值可以是任何值(包括 null 或未定义),而 TypeScript 强制您在编译时正确处理这一事实,以便您的代码不会在运行时崩溃。
您正在查看的示例代码是纯 JavaScript,没有任何类型检查。假设快照不会为空或未定义。如果您发现这令人困惑或有问题,请使用文档页面顶部的“发送反馈”链接来解释让您感到困惑的内容。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)