有条件的 React Hooks

React Hooks with Conditions

我写了一个使用反应钩子的组件,它看起来像

  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 中检查这种情况是否是一种好的做法?

出于性能原因并根据您的代码,最好仅在 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}
        />
      );
    })}
  </>
  );
}

请参阅有关处理带条件的挂钩的文档。 https://reactjs.org/docs/hooks-rules.html