javascript - 未存储 URL 的 React Firestore 图像数组
问题描述
class App extends React.Component {
constructor(props) {
super(props);
this.addData = this.addData.bind(this);
this.state = {
username: "",
imgFile: [],
imgUrl: [],
};
}
upload = (e) => {
e.preventDefault();
this.storeImageAndgetUrl(this.addData);
};
storeImageAndgetUrl = (addData) => {
const imgUrl = [];
const storage = fire.storage();
const ref = storage.ref();
this.state.imgFile.forEach((file) => {
ref
.child(file.name)
.put(file)
.then(
(snapShot) => {
console.log(snapShot);
const storage = fire.storage();
this.state.imgFile.forEach((file) => {
const ref = storage.ref(file.name);
ref.getDownloadURL().then((fireBaseUrl) => {
console.log(fireBaseUrl);
imgUrl.push(fireBaseUrl);
});
});
this.setState({ imgUrl });
},
(err) => {
console.log(err);
}
);
});
addData();
};
addData = () => {
// const images = this.state.imgUrl;
console.log(this.state.imgUrl);
fire.firestore().collection("new").add({
name: this.state.username,
img: this.state.imgUrl,
});
};
handleChangeUsername = (e) => {
this.setState({ [e.target.name]: e.target.value });
};
setImage = (e) => {
if (Array.from(e.target.files[0]).length < 4) {
const img = Array.from(e.target.files);
this.setState({ imgFile: img });
} else {
alert("You can select maximum 5 Images");
}
};
render() {
console.log(this.state.username);
console.log(this.state.imgFile);
console.log(this.state.imgUrl);
return (
<div className="App">
<form onSubmit={this.upload}>
<label>Username:</label>
<input
type="text"
value={this.state.username}
name="username"
onChange={this.handleChangeUsername}
/>
<input
type="file"
accept="image/*"
onChange={this.setImage}
multiple
/>
<button type="submit">Submit</button>
</form>
</div>
);
}
}
export default App;
在上面的代码中,我存储了多个图像数组,并使用回调获取这些图像的 URL,并将 URL 存储在 firestore 中。未存储 URL 的图像数组。我已经创建了一个回调函数,我在其中存储图像和另一个函数,其中 Fetched URL Array 存储在 firestore
解决方案
推荐阅读
- javascript - 来自 Vue 的动画画布
- reactjs - What is the correct value for a `defaultProp` that corresponds to a `PropTypes.element`?
- python - "Could not connect to display" on EC2 Server
- matlab - 如何从 x,y,z,v 数据中获取切片图?
- php - How to get Apache and MySQL logs in PHP
- c++ - 如何解决代码中的“未声明的标识符”错误?
- google-apps-script - 如何在 AppMaker 的下拉小部件中手动设置值?
- javascript - 传递给 promise.then 的布尔值是什么意思
- javascript - Inline Javascript stoped adding class to element
- java - Time spent at a specific location using GPS sensor