简体   繁体   English

State 在 React 中不会立即更新

[英]State doesn't update immediately in React

I know I have to use useEffect but I couldn't figure out a way to make this code to work.我知道我必须使用 useEffect 但我想不出一种方法来使这段代码工作。 I want the state courses to be updated immediately every single time I'm adding a new course.我希望每次添加新课程时都能立即更新 state 课程。 The data variable in the getCourses function is updated, but the update of the state doesn't happen immediately. getCourses function 中的数据变量已更新,但 state 的更新不会立即发生。

function CourseList() {
const [courses, setCourses] = useState([]);
const [idProf, setIdProf] = useState();

this function gets the list of courses from the database and store it in courses此 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
}

this function adds a course and then adds the professor stored in idProf to this course这个 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);
}

I tried to use useEffect but it s updating the state only one time我尝试使用 useEffect 但它只更新一次 state

useEffect(()=>{
    getCourses();
},[]);

the courses are not updated when this function is running此 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>)

} }

Your getCourses funciton is async, but you are not awaiting it.您的 getCourses 功能是异步的,但您并没有等待它。 Try await getCourses() .尝试await getCourses()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM