【发布时间】:2021-09-18 02:56:19
【问题描述】:
我目前正在使用 React 和 Firebase 开展一个项目,目前我将新数据写入 Firestore 的逻辑直接在我的组件中。我现在也在集成 Redux,为此我正在使用 react-redux-firebase。我现在的问题是,把这个逻辑放在哪里最好,因为它让我的组件变得臃肿。
在react-redux-firebase的documentation中,他们也直接放在了组件里,但是他们的逻辑很简单,我的稍微复杂一点,比如这个handleSubmit:
const handleSubmit = async (e) => {
e.preventDefault();
setDisabled(true); //disable button to prevent multiple sbumits
setLoading(true);
try {
const docRef = await firestore.collection("goodies").add(newGoodieData); // create new event
await firestore.collection("goodies").doc(docRef.id).update({
// add eventId to event doc
id: docRef.id,
});
if (image) {
const imageName = docRef.id + "." + image.name.split(".").pop(); //create image name with eventID and file extions
const imageRef = storage.ref().child("goodie_images/").child(imageName); //create imageRef
const imageSnapshot = await imageRef.put(image); //upload image to storage
const downloadUrl = await imageSnapshot.ref.getDownloadURL(); //get image download-url
const imagePath = imageRef.fullPath; // get image storage path
await firestore.collection("goodies").doc(docRef.id).update({
//update event with imageUrl and imagePath
image: downloadUrl,
imagePath: imagePath,
});
}
setDisabled(false);
setLoading(false);
dispatch(showSuccessToast(`Created new goodie "${newGoodieData.name}"!`));
history.push("/goodies");
} catch (error) {
dispatch(showErrorToast("Ops, an error occurred!"));
console.error(error.message);
}
};
【问题讨论】:
标签: reactjs firebase react-redux-firebase