React.js中使用uuid向Firebase上传ID时存储异常怎么解决?
问题根因
JS 中支持${变量}插值的模板字符串必须使用**反引号()**包裹,你当前代码中.ref('posts/${id}')使用了单引号包裹,导致${id}不会被解析为变量,直接作为普通文本存储。你代码中特意添加的// eslint-disable-next-line no-template-curly-in-string`注释也刚好佐证了这一写法不符合JS语法规范,是为了屏蔽报错临时添加的。
修复方案
将对应位置的单引号替换为反引号即可,修改后的代码片段如下:
import { v4 as uuid } from 'uuid'; const sendPost = () => { const id = uuid(); const uploadTask = storage // 原单引号改为反引号,不需要再保留ESLint屏蔽注释 .ref(`posts/${id}`) .putString(cameraImage, "data_url"); uploadTask.on( "state_changed", null, (error) => { console.log(error); }, () => { storage .ref("posts") .child(id) .getDownloadURL() .then((url) => { db.collection("posts").add({ imageUrl: url, username: "TEST", read: false, timstamp: firebase.firestore.FieldValue.serverTimestamp(), }); history.replace("/chats"); }); } ); };
内容的提问来源于stack exchange,提问作者K Lee
相关产品推荐
相关产品推荐

