javascript - 如何在 React JS 中执行基于条件的不重复自己(干)原则?

标签 javascript reactjs npm react-hooks dry

code output

组件使用方式:

  import React from "react";
  import MyAvatars from "../../components/MyAvatar/MyAvatars";

  const About = () => {
   return (
  
    <MyAvatars
      topType={[true, 1000]}
      accessoriesType={[true, 1200]}
      facialHairType={["blank"]}
    />
   );
 };

 export default About;

这是我的代码。 我目前正在研究这个问题。

代码:

  import React from "react";
  import Avatar from "avataaars";
  import { Top, Accessories, FacialHair } from "./avatarThings";

  const MyAvatar = ({ topType, facialHairType }) => {
  
  const [avatar, setAvatar] = React.useState({
      avatarStyle: "Circle",
      topType: "ShortHairDreads01",
      accessoriesType: "Blank",
      facialHairType: "Blank",
});


const topFunc = () =>{
    if (topType.length === 2) {
      const interval = setInterval(() => {
        setAvatar((prev) => {
          return {
            ...prev,
            topType:  Top[Math.floor(Math.random() * Top.length)],
          };
        });
      }, topType[1]); //this is time
      return () => clearInterval(interval);
    }
    setAvatar((prev) => {
      return {
        ...prev,
        topType: topType[0],
      };
    });
}

const FacialHairFunc = () =>{
      if (facialHairType.length === 2) {
      const interval = setInterval(() => {
        setAvatar((prev) => {
          return {
            ...prev,
            facialHairType: FacialHair[Math.floor(Math.random() * FacialHair.length)],
          };
        });
      }, facialHairType[1]);
      return () => clearInterval(interval);
    }
    setAvatar((prev) => {
      return {
        ...prev,
        facialHairType: facialHairType[0],
      };
    });
}

React.useEffect(() => {

  if (topType) {
    topFunc()
  }
  if (facialHairType) {
    FacialHairFunc()
  }

}, [])


return (
  <Avatar
    avatarStyle="Circle"
    topType={avatar.topType}
    accessoriesType={avatar.accessoriesType}
    hairColor={avatar.hairColor}
    facialHairType={avatar.facialHairType}
  />

 );
};

export default MyAvatar;

我是编程新手。 我目前正在创建一个有用的开源 NPM 包

这是它的代码。 一遍又一遍地重复相同的代码。

我希望我能比这更容易地修改这段代码,但我做不到。 人们很容易钦佩你。 我将通过您为此编写的代码学习新东西。

如果您能提供帮助,我将非常高兴。

请帮忙并让我知道您的贡献

谢谢:)

最佳答案

有效计算随机属性的函数与更新头像状态的方面之间存在一些耦合。

我建议将选择随机属性并更新状态的每个“属性”函数转换为单个React钩子(Hook),该钩子(Hook)采用属性数组和间隔,并返回随机属性,然后将每个随机选择的属性直接传递给Avatar 组件。没有令人信服的理由让组件中具有中间 avatar 状态。

示例:

const getRandomAttribute = arr => arr[Math.floor(Math.random() * arr.length)];

const useRandomAttribute = (attributes = [], valueArr = []) => {
  const [attribute, setAttribute] = useState(() => {
    if (valueArr[0]) {
      return getRandomAttribute(attributes);
    }
  });

  useEffect(() => {
    let timerId;
    if (valueArr[0] && valueArr[1] > 0) {
      timerId = setInterval(() => {
        const attribute = getRandomAttribute(attributes);
        setAttribute(attribute);
      }, valueArr[1]);
    }
    return () => clearTimeout(timerId);
  }, [attributes, valueArr]);

  return attribute;
};

应用程序

import React from "react";
import Avatar from "avataaars";
import { Top, Accessories, FacialHair, ..... } from "./avatarThings";

const MyAvatar = ({ topType, facialHairType, accessoriesType, hairType }) => {
  const accessory = useRandomAttribute(Accessories, accessoriesType);
  const face = useRandomAttribute(FacialHair, facialHairType);
  const hair = useRandomAttribute(Hair, hairType);
  const top = useRandomAttribute(Top, topType);

  return (
    <Avatar
      avatarStyle="Circle"
      topType={top || "ShortHairDreads01"}
      accessoriesType={accessory || "Blank"}
      hairColor={hair || "BrownDark"}
      facialHairType={face || "Blank"}
      clotheType="Hoodie"
      clotheColor="Red"
      eyeType="Wink"
      eyebrowType="Default"
      mouthType="Smile"
      skinColor="Brown"
    />
  );
};

您可以从此处调整代码的间隔时间、其他默认/后备值等。

Edit how-to-do-condition-based-dont-repeat-yourself-dry-principle-in-react-js

关于javascript - 如何在 React JS 中执行基于条件的不重复自己(干)原则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71244031/

相关文章:

javascript - 如何获得点击按钮的值?

javascript - 使用 Meteor 时,我应该在 npm 前面加上 Meteor 前缀吗?

visual-studio-2015 - Visual Studio 2015 中的 NPM 不会安装任何东西

node.js - 安装 Node 后找不到 NPM 命令

javascript - 按类将函数应用于 div

javascript - return false 在 then 中不起作用,并且使用 lodash 绑定(bind)函数

javascript - React 如何区分用于求值的大括号和用作 JS 的大括号?

ios - CSS iOS - 为什么 :hover persist through states

javascript - Google Feed API 是否支持通过 Node.js 进行访问?

javascript - 使用 javascript 的 3d 曲面图?