初始化后如何使用useState的值
how to use value of useState after init it
我这些状态挂钩:
const [features, setFeatures] = useState([])
const [medicalProblem, setMedicalProblem] = useState([])
我的 medicalProblem
变量将以 api 的响应初始化:
useEffect(() => {
getMedicalProblem()
}, []);
const initFeatures = (index) => {
let mfeatures = medicalProblem[index].features //I got Cannot read properties of undefined (reading 'features') error
mfeatures.sort(function (a, b) {
return a.order - b.order;
});
setFeatures(mfeatures)
}
const getMedicalProblem = () => {
api
.get("dental/generic/slideshow/medical-problem/")
.then((res: any) => {
const { count, results } = res
setMedicalProblem(results)
initFeatures(0)
})
.catch((err) => {
});
};
但是我得到了这个错误:
Cannot read properties of undefined (reading 'features')
有几种方法可以完成此操作,但最简单的可能是创建另一个依赖于 medicalProblems 数组的 useEffect 挂钩,如下所示!
useEffect(() => {
if (medicalProblems) {
initFeatures(0)
}
}, [medicalProblems])
这个额外的钩子将确保在继续初始化您的功能之前填充您的 medicalProblems。让我知道这是否有效!
我这些状态挂钩:
const [features, setFeatures] = useState([])
const [medicalProblem, setMedicalProblem] = useState([])
我的 medicalProblem
变量将以 api 的响应初始化:
useEffect(() => {
getMedicalProblem()
}, []);
const initFeatures = (index) => {
let mfeatures = medicalProblem[index].features //I got Cannot read properties of undefined (reading 'features') error
mfeatures.sort(function (a, b) {
return a.order - b.order;
});
setFeatures(mfeatures)
}
const getMedicalProblem = () => {
api
.get("dental/generic/slideshow/medical-problem/")
.then((res: any) => {
const { count, results } = res
setMedicalProblem(results)
initFeatures(0)
})
.catch((err) => {
});
};
但是我得到了这个错误:
Cannot read properties of undefined (reading 'features')
有几种方法可以完成此操作,但最简单的可能是创建另一个依赖于 medicalProblems 数组的 useEffect 挂钩,如下所示!
useEffect(() => {
if (medicalProblems) {
initFeatures(0)
}
}, [medicalProblems])
这个额外的钩子将确保在继续初始化您的功能之前填充您的 medicalProblems。让我知道这是否有效!