这是我的代码。我正在从支持中获取学生的数据,对其进行过滤。我无法为选择选项设置默认值,而且两者都setAssignedStudent
不起作用,在控制台中,我得到undefined
. 请让我知道如何解决这个问题。
//here is sample of students array
// let students- [ {name: "abc", email:"abc.com", mentor:"" },
// {name: "abc", email:"abc.com", mentor:"cda" }, {name: "abc", email:"abc.com", //mentor:"" }]
useEffect(() => {
const getStudents = async () => {
try {
const res = await fetch("http://localhost:3001/students");
const data = await res.json();
//console.log(data);
//filtering students based on who doesn;t have mentor
let filter = data.filter((e) => {
return e.mentor === "";
});
if (filter.length > 0) setStudents(filter);
} catch (err) {
console.log(err);
}
};
getStudents();
}, []);
const [assignedStudent, setAssignedStudent] = useState(students[1]);
const handleChange = (e) => {
setAssignedStudent(
students.find((student) => student._id == e.target.value)
);
console.log(assignedStudent);
};
const handleSubmit = async (e) => {
e.preventDefault();
console.log(assignedStudent);
}
<form onSubmit={(e) => handleSubmit(e)}>
<select onChange={handleChange} value={assignedStudent}>
{students.map((student) => {
return (
<>
<option key={student._id} value={student.id}>
{student.name}
</option>
</>
);
})}
</select>
<button type="submit">Submit </button>
</form>