我已经编写了一个使用react钩子的组件,它看起来像
export default props => {
const [educations, setEducations] = useState([]);
const [isAdd, setAdd] = useState(false);
const [currentedcuation, setCurrentEducation] = useState(defaultEducation);
const [currentid, setCurrentId] = useState("-1");
useEffect(() => {
if (typeof props.currentProfileInfo !== "undefined") {
if (props.currentProfileInfo) {
if (educations.length === 0) {
setEducations([...props.currentProfileInfo.education]);
}
}
}
});
return (
<>
{educations.map(item => {
return (
<EducationElement
key={item.id}
id={item.id}
type={props.type}
education={item}
currentedcuation={currentedcuation}
isAdd={item.id === "-1" || item.id === currentid ? isAdd : false}
onSave={onSave}
onEdit={onEdit}
dataChanged={dataChanged}
/>
);
})}
</>
);
}基本上,它将根据数组来渲染子组件,所以我的问题是,当我的组件加载时,我需要检查条件,比如
useEffect(() => {
if (typeof props.currentProfileInfo !== "undefined") {
if (props.currentProfileInfo) {
if (educations.length === 0) {
setEducations([...props.currentProfileInfo.education]);
}
}
}所以我只想确认一下,在useEffect中检查这种情况是不是一种很好的做法?
发布于 2019-01-30 19:28:04
出于性能原因并基于您的代码,最好仅在props.currentProfileInfo更改时执行useEffect钩子。你可以像这样改进你的代码
export default props => {
const [educations, setEducations] = useState([]);
const [isAdd, setAdd] = useState(false);
const [currentedcuation, setCurrentEducation] = useState(defaultEducation);
const [currentid, setCurrentId] = useState("-1");
useEffect(() => {
if (props.currentProfileInfo && educations.length === 0) {
setEducations([...props.currentProfileInfo.education]);
}
}, [props.currentProfileInfo]);
return (
<>
{educations.map(item => {
return (
<EducationElement
key={item.id}
id={item.id}
type={props.type}
education={item}
currentedcuation={currentedcuation}
isAdd={item.id === "-1" || item.id === currentid ? isAdd : false}
onSave={onSave}
onEdit={onEdit}
dataChanged={dataChanged}
/>
);
})}
</>
);
}发布于 2019-11-15 20:37:11
带条件的钩子的处理请参考文档。https://reactjs.org/docs/hooks-rules.html
https://stackoverflow.com/questions/54439321
复制相似问题