[英]State doesn't update immediately in React
我知道我必須使用 useEffect 但我想不出一種方法來使這段代碼工作。 我希望每次添加新課程時都能立即更新 state 課程。 getCourses function 中的數據變量已更新,但 state 的更新不會立即發生。
function CourseList() {
const [courses, setCourses] = useState([]);
const [idProf, setIdProf] = useState();
此 function 從數據庫中獲取課程列表並將其存儲在課程中
const getCourses = async () =>{
const response = await fetch(`${SERVER}/api/courses`);
const data = await response.json();
setCourses(data);
// -> here setCourses doesnt update the state, but data has the updated array of courses
}
這個 function 添加一門課程,然后將存儲在 idProf 中的教授添加到該課程中
const addCourse = async(course) => {
//...fetch with post method...//
getCourses(); // here i call the method but when I'm trying to add the professor to the course on the next line, the state isn't updated yet
addStudentCourse(idProf, course.cod);
}
我嘗試使用 useEffect 但它只更新一次 state
useEffect(()=>{
getCourses();
},[]);
此 function 正在運行時,課程未更新
const addStudentCourse = async(idStudent,codCourse)=>{
let id = -1;
//searching for the id in courses
for(let c of courses){
if(c.cod == codCourse){
id = c.id;
}
}
console.log(id)// id is still -1, it cant find the course because the state wasnt updated yet
if(id != -1){
//..adding to the database..//
}
}
return (<div></div>)
}
您的 getCourses 功能是異步的,但您並沒有等待它。 嘗試await getCourses()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.