如何将输入数据存储为数组中的对象?
How to store input data as objects in an array?
如何使用 useState
将输入数据作为对象存储在数组中?请帮忙。
我需要帮助。我无法获得所需的输出来显示输入值。
const Form = () => {
const [allNotes, setAllNotes] = useState([{}]);
const [notes, setNotes] = useState({
name: "",
age: "",
class: "",
request: "",
});
const nameChangeHandler = (event) => {
setNotes((prevState) => {
const newState = { ...prevState, name: event.target.value };
return newState;
});
};
const ageChangeHandler = (event) => {
setNotes((prevState) => {
const newState = { ...prevState, age: event.target.value };
return newState;
});
};
const classChangeHandler = (event) => {
setNotes((prevState) => {
const newState = { ...prevState, class: event.target.value };
return newState;
});
};
const requestChangeHandler = (event) => {
setNotes((prevState) => {
const newState = { ...prevState, request: event.target.value };
return newState;
});
};
const submitHandler = () => {
setAllNotes((prevState) => {
const newState = {
...prevState,
name: notes.name,
age: notes.age,
class: notes.class,
request: notes.request,
};
return newState;
});
};
一切看起来都不错,也许除了两个小错误:
让我们让 all notes
的初始状态只是一个空数组,比如
const [allNotes, setAllNotes] = useState([]);
setAllNotes
里面的新数组应该是array而不是object,比如:
const submitHandler = () => {
setAllNotes((prevState) => {
const newState = [
...prevState,
{
name: notes.name,
age: notes.age,
class: notes.class,
request: notes.request,
}
];
return newState;
});
};
希望这能奏效!
如何使用 useState
将输入数据作为对象存储在数组中?请帮忙。
我需要帮助。我无法获得所需的输出来显示输入值。
const Form = () => {
const [allNotes, setAllNotes] = useState([{}]);
const [notes, setNotes] = useState({
name: "",
age: "",
class: "",
request: "",
});
const nameChangeHandler = (event) => {
setNotes((prevState) => {
const newState = { ...prevState, name: event.target.value };
return newState;
});
};
const ageChangeHandler = (event) => {
setNotes((prevState) => {
const newState = { ...prevState, age: event.target.value };
return newState;
});
};
const classChangeHandler = (event) => {
setNotes((prevState) => {
const newState = { ...prevState, class: event.target.value };
return newState;
});
};
const requestChangeHandler = (event) => {
setNotes((prevState) => {
const newState = { ...prevState, request: event.target.value };
return newState;
});
};
const submitHandler = () => {
setAllNotes((prevState) => {
const newState = {
...prevState,
name: notes.name,
age: notes.age,
class: notes.class,
request: notes.request,
};
return newState;
});
};
一切看起来都不错,也许除了两个小错误:
让我们让
all notes
的初始状态只是一个空数组,比如const [allNotes, setAllNotes] = useState([]);
setAllNotes
里面的新数组应该是array而不是object,比如:
const submitHandler = () => {
setAllNotes((prevState) => {
const newState = [
...prevState,
{
name: notes.name,
age: notes.age,
class: notes.class,
request: notes.request,
}
];
return newState;
});
};
希望这能奏效!