这里的这个函数已经给我带来了一些麻烦。
当打印";res";它显示对象及其字段很好,但是当循环外的数据未定义时,考虑到变量仅在函数内初始化,这是可以理解的。
但是,如果我尝试使用里面的setData(字段(或setServerUser(字段(,它会递归执行。
我认为解决方案是在循环外调用setData(字段(或setServerUser(字段(,尽管结果相同。
代码:
const [ serverUser, setServerUser ]=useState('')
const [ data, setData ]=useState('')
async function fetchProfile(){
const res = await fetch(
"http://XXX.XXX.XXX.XXX:8080/User/getByEmail", {
method: "POST",
headers:{"Content-Type":"application/json"},
body:JSON.stringify( { email : user.email } ) } )
const data = res.json().then((res) => {
// V both of these causes infinite looping
// V i dont think this is the right spot to set - but res doesnt exist outside
//setServerUser(res)
//setData(res)
console.log(res) // < this actually prints the object perfectly
});
console.log(res) // < equal to undefined here
// V both of these causes infinite looping
// V this makes the most sense to me setting here but yet same result
//setServerUser(data);
//setData(data)
console.log("data" + data) // < this returns data[object Promise]
}
fetchProfile();
与useEffect、useState及其相互覆盖有关
const [ serverUser, setServerUser ]=useState('')
//3. passing an empty array for on mount (when the page loads)
useEffect(() => {
fetch("http://XXX.XXX.XXX:8080/User/getByEmail", {
method: "POST",
headers:{"Content-Type":"application/json"},
body:JSON.stringify( { email : user.email } )
})
.then(response => response.json())
.then(json => { setServerUser(json) })
},[])