Я написал один компонент, который использует хуки реакции, и он выглядит так:
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?





Из соображений производительности и исходя из вашего кода было бы неплохо выполнять хук useEffect только при изменении props.currentProfileInfo. Вы можете улучшить свой код, например
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}
/>
);
})}
</>
);
}
Пожалуйста, смотрите документацию по работе с хуками с условиями. https://reactjs.org/docs/hooks-rules.html