如何获取要保存在firestore中的复选框的值?



我有这个复选框,用户可以选中所有的复选框。我无法将其保存在firestore中,因为每次提交时都会出现错误,并显示:

TypeError: s.indexOf is not a function

如果我选中所有的复选框然后选择console.log(state);它会显示如下:

item1: true
item2: true
item3: true

我想要的只是当特定的复选框(item1和item2)被点击时,它会输出如下内容:

item1 
item2

以下是完整的代码:

const component = (props) => {
const [state, setState] = useState({
Fever: false,
Headache: false,
Nausea: false,
"Muscle Pain": false,
});
const handleCheckbox = (event) => {
console.log(event.target.value);
setState({ ...state, [event.target.name]: event.target.checked });
};
const handleSubmit = (e) => {
e.preventDefault();
for (const p in state) {
if (!state[p]) delete state[p];
}
try {
const userRef = firestore.collection("users").doc(uid);
const ref = userRef.set({
state,
});
console.log(" saved");
} catch (err) {
console.log(err);
}
};
return (
<Container>
<form onSubmit={handleSubmit}>
<FormGroup style={{ alignContent: "center", padding: "1rem" }}>
<FormControlLabel
control={
<Checkbox
checked={state.Fever}
name="Item1"
color="primary"
value="Item1"
onChange={handleCheckbox}
/>
}
label="Item1"
/>
<FormControlLabel
control={
<Checkbox
checked={state.Headache}
name="Item2"
color="primary"
value="Item2"
onChange={handleCheckbox}
/>
}
label="Item2"
/>
<FormControlLabel
control={
<Checkbox
checked={state.Nausea}
name="Item3"
color="primary"
value="Item3"
onChange={handleCheckbox}
/>
}
label="Item3"
/>

</FormGroup>
<Button type="submit">Submit</Button>
<br />
</form>
</Container>
);
};
export default component;

我如何获得item1、item2和item3的值,以便我可以将其保存在firestore中?谢谢你。

你可以试试这个吗

const handleSubmit = (e) => {
e.preventDefault();
const newState = {...state};
for (const p in newState) {
if (!newState[p]) delete newState[p];
}
try {
const userRef = firestore.collection("users").doc(uid);
const ref = userRef.set({
newState,
});
console.log(" saved");
} catch (err) {
console.log(err);
}
};

最新更新