与条件反应挂钩

时间:2019-01-30 11:15:38

标签: reactjs react-hooks

我已经编写了一个使用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中检查这种情况是否是一种好习惯?

2 个答案:

答案 0 :(得分:0)

出于性能原因,并且基于您的代码,仅当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}
        />
      );
    })}
  </>
  );
}

答案 1 :(得分:0)

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

相关问题