我有這個帶有多個復選框的表單,在它下面,我還有others用戶可以輸入任何值的地方。問題是,如果我第二次輸入一個值,它將洗掉用戶之前輸入的值。
假設我已經進入books了我的第一次提交。現在,我想再次提交另一個值others,但這次是movies. 我想將這兩個值保存在 firestore 中;books和movies。問題是,如果我要提交movies,這將覆寫前一個books,這意味著它將替換books. 如何避免這種情況并同時顯示用戶在欄位中輸入的多個值others?
下面是代碼:
const sample = (props) => {
const [others, setOthers] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
try {
const user = firestore.collection("users").doc(id);
const ref = user.set(
{
1: {
choices,
others
}
},
{ merge: true }
);
console.log(" saved");
} catch (error) {
console.log(error);
}
};
return (
<>
<form onSubmit={handleSubmit}>
<FormGroup>
//codes for the checkboxes here
<TextField
type="text"
label="Others:"
value={others}
onChange={(e) => setOthers(e.target.value)}
multiline
/>
</FormGroup>
<button type="submit">Submit</button>
<br />
</form>
</>
);
};
export default sample;
uj5u.com熱心網友回復:
我要以我不熟悉 react 的方式作為開頭,但我確實經常使用 firestore。所以語法對你來說可能不同。
但是我注意到的第一件事是您正在使用const ref = user.set該檔案。這是第一次創建檔案時很好,但是如果您在現有檔案上使用“.set”,它將使用您嘗試更新它的任何內容覆寫該檔案中的所有資料。
您應該用于const ref = user.update更新檔案中的欄位。
第二位是說你想更新“其他”欄位。即使您使用“.update”,它仍然會覆寫該欄位中的資料。update 就是這樣做的,它使用您嘗試更新的內容來更新相關欄位。你想要做的是添加它。
所以你的“others”欄位需要是一個陣列,為了在不覆寫以前的資料的情況下向其中添加新值,你需要使用arrayUnion。
const handleSubmit = (e) => {
e.preventDefault();
try {
const user = firestore.collection("users").doc(id);
const ref = user.update(
{
1: {
choices,
others: firebase.firestore.FieldValue.arrayUnion(others),
}
},
{ merge: true }
);
console.log(" saved");
} catch (error) {
console.log(error);
}
};
現在我不知道匯入是如何在反應中作業的,但在 VUEjs 中,您需要import firebase from "firebase/compat/app";在腳本標簽中匯入才能使用該 firebase 功能。
如果你想從其他陣列中洗掉一個專案然后使用。
const handleSubmit = (e) => {
e.preventDefault();
try {
const user = firestore.collection("users").doc(id);
const ref = user.update(
{
1: {
choices,
others: firebase.firestore.FieldValue.arrayRemove(item), //item = whatever it is you're trying to remove.
}
},
{ merge: true }
);
console.log(" saved");
} catch (error) {
console.log(error);
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/395538.html
標籤:javascript 反应 火力基地 谷歌云firestore
上一篇:如何用空格顯示這些值以分隔單詞?
下一篇:在滾動時更改div背景顏色
