我正在一个功能组件中使用 React 的状态钩子来从数据库中获取治疗师。从中我看到,在useEffect((中,setTherapists([therapists].concat(therapists((;是,该列表以无限递归调用。我看不出问题出在哪里,或者我需要如何正确调用列表。
在我正确获取治疗师数组后,我需要渲染所有治疗师。这就是我的想法,但我不知道如何使用 Hooks State 编写:
function renderTherapists() {
const items = this.state.therapists.map( (t, idx) => (
<TherapistCard therapist={t} key={idx} />
))
return (
<div ref={0} className="therapist-list">
{ items }
</div>
)
}
我当前的功能组件:
function TypeArticleOne(props) {
const [ therapists, setTherapists ]= useState([]);
const [speciality, setSpeciality]= useState('ABA');
const [pageLoading, setPageLoading]= useState(true);
const topProfilesUrl = 'therapists/top/profiles'
useEffect(() => {
console.log(speciality);
getTopTherapists();
window.scrollTo(0, 0);
}, []);
const getTopTherapists = () => {
setPageLoading(true);
loadTopTherapists();
};
const loadTopTherapists = () => {
console.log("second");
props.actions.reqGetTherapistsTopProfiles({
body: {},
headers: null,
resource: `${topProfilesUrl}`
})
};
useEffect(() => {
let apiData = props.apiData;
if (apiData.topProfiles && apiData.topProfiles.success) {
const therapists = apiData.topProfiles.therapists;
setPageLoading(false);
setTherapists([therapists].concat(therapists));
}
}, [pageLoading, therapists]);
您需要将props 中的治疗师传递给 useState 声明的默认值:
const [ therapists, setTherapists ] = useState(apiData.topProfiles.therapists);
因此,当它被重新渲染时,它不会在循环中再次被调用。
恒定的治疗师正在从您的外部范围中隐藏治疗师列表。
if (apiData.topProfiles && apiData.topProfiles.success) {
const therapists = apiData.topProfiles.therapists;
setPageLoading(false);
setTherapists([therapists].concat(therapists));
}
此外,由于它已经是一个数组,您可以调用 concat 方法,而无需将列表放在括号 [] 内。
喜欢:
const loadedTherapists = apiData.topProfiles.therapists;
setPageLoading(false);
setTherapists(therapists.concat(loadedTherapists));