Реакция крючков с условиями - PullRequest
0 голосов
/ 30 января 2019

Я написал один компонент, использующий перехватчики реагирования, и он выглядит так:

  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?

1 Ответ

0 голосов
/ 30 января 2019

По соображениям производительности и исходя из вашего кода, было бы неплохо выполнять ловушку 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}
        />
      );
    })}
  </>
  );
}
...