首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React Hooks with Condition

React Hooks with Condition
EN

Stack Overflow用户
提问于 2019-01-30 19:15:38
回答 2查看 7.9K关注 0票数 0

我已经编写了一个使用react钩子的组件,它看起来像

代码语言:javascript
复制
  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}
        />
      );
    })}
  </>
  );
}

基本上,它将根据数组来渲染子组件,所以我的问题是,当我的组件加载时,我需要检查条件,比如

代码语言:javascript
复制
useEffect(() => {
    if (typeof props.currentProfileInfo !== "undefined") {
      if (props.currentProfileInfo) {
        if (educations.length === 0) {
          setEducations([...props.currentProfileInfo.education]);
        }
      }
    }

所以我只想确认一下,在useEffect中检查这种情况是不是一种很好的做法?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-01-30 19:28:04

出于性能原因并基于您的代码,最好仅在props.currentProfileInfo更改时执行useEffect钩子。你可以像这样改进你的代码

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2019-11-15 20:37:11

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

票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54439321

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档