作为uni项目的一部分,我正在为牙科医学设计一个react页面,我对react和javascript相当陌生。
现在我有了一个健康声明页面,页面上有一组开关,可以根据状态改变颜色。当用户登录并进入其健康声明页面时,我希望加载他保存的以前的值一次,然后仅在他按下刷新时加载。
我的函数代码如下所示:
import { useState, useEffect } from "react";
import authHeader from "../../security/AuthHeader";
import axios from "axios";
import "../ToggleSwitch.css";
const ToggleSwitch = (userid) => {
const API_URL = "http://localhost:8081/api/doh/";
const switchState = {
asthma: "off",
infectiousDisease: "off",
bleedingDisorder: "off",
cancer: "off",
diabetes: "off",
epilepsy: "off",
hivAids: "off",
stroke: "off",
heartDisease: "off",
hbp: "off",
immuneDisorders: "off",
lungDisease: "off",
mentalDisorder: "off",
rheumaticDisease: "off",
smokeTobaccoProducts: "off",
radiationTherapy: "off",
eatingDisorders: "off",
entDisorders: "off",
latex: "off",
localAnasthetics: "off",
metals: "off",
penicillin: "off",
pollen: "off",
foods: "off",
bleedingGums: "off",
bruxism: "off",
halitosis: "off",
ulcer: "off",
dryMouth: "off",
soreJawM: "off",
};
const [patientInfo, setPatientInfo] = useState({
name: "",
surname: "",
gender: "",
dob: "",
});
const [message, setMessage] = useState();
const [medications, setMedications] = useState("");
const [otherInfo, setOtherInfo] = useState("");
const [values, setValues] = useState({});
const getDoH = async (userid) => {
try {
const auth = authHeader();
let config = {
headers: {
"Content-Type": "application/json",
Authorization: auth.Authorization,
},
params: {
userid: userid,
},
};
return await axios.get(API_URL + "getdohadmin", config);
} catch (e) {
console.log("Failet to get DoH");
}
};
useEffect(() => {
getDoH(userid).then(
(response) => {
let newValues = switchState;
let valueArray = Object.entries(newValues).map((v, index) => {
v[1] = response.data.switchValues[index];
return v;
});
newValues = Object.fromEntries(valueArray);
setValues({ ...newValues });
newValues = patientInfo;
valueArray = Object.entries(newValues).map((v, index) => {
v[1] = response.data.patientInformation[index];
return v;
});
newValues = Object.fromEntries(valueArray);
setPatientInfo({ ...newValues });
setMedications(response.data.medications);
setOtherInfo(response.data.otherInfo);
},
(error) => {
console.log(error);
}
);
}, []);
const handleChangeMed = (e) => {
setMedications(e.target.value);
};
const handleChangeOtherInfo = (e) => {
setOtherInfo(e.target.value);
};
const handleChangePatientInfo = (e) => {
const { name, value } = e.target;
setPatientInfo({
...patientInfo,
[name]: value,
});
};
const toggle = (name, value) => (e) => {
console.log("Toggle", name, value);
if (value === "off") {
setValues({
...values,
[name]: "on",
});
} else if (value === "on") {
setValues({
...values,
[name]: "off",
});
}
};
const upload = async (event) => {
try {
const auth = authHeader();
let formData = new FormData();
const switchValues = Object.values(values);
const patientInformation = Object.values(patientInfo);
formData.set("patientInformation", patientInformation);
formData.set("switchValues", switchValues);
formData.set("medications", medications);
formData.set("otherInfo", otherInfo);
event.preventDefault();
setMessage("Declaration of health uploaded successfully!");
return await axios.post(API_URL + "upload", formData, {
headers: {
"Content-Type": "application/json",
Authorization: auth.Authorization,
},
});
} catch (e) {
setMessage("Declaration of health failed to upload!");
}
};
//If you only want to run the function given to useEffect after the initial render,
//you can give it an empty array as second argument.
return {
toggle,
handleChangeMed,
handleChangeOtherInfo,
upload,
handleChangePatientInfo,
patientInfo,
values,
medications,
otherInfo,
message,
};
};
export default ToggleSwitch;
现在,与useeffect部分相关的代码存在一些问题。如果我像这样保留代码,我会在控制台中收到以下消息:
Line 134:6: React Hook useEffect has missing dependencies: 'patientInfo', 'switchState', and 'userid'. Either include them or remove the dependency array
我还注意到,在我的api中,即使我刷新项目中与健康声明无关的其他页面,也会调用健康声明的useeffect。
现在,如果我继续添加依赖项,我会得到一个永恒的循环,我注意到这是因为我的api变得疯狂,不断发送健康声明的值。
在控制台中,我有时会收到以下警告:
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
iv花费数小时阅读useeffect、useinitialstate等。但我似乎找不到解决这个问题的好办法。如何更改此代码以避免内存泄漏或无限循环?
暂无答案!
目前还没有任何答案,快来回答吧!