0

所以我正在完成这个任务,我将原始 html 转换为一个反应组件,我需要完成这个任务 4 次,导航栏中的 4 个菜单。代码有效,但是代码看起来很难看,我相信有一种方法可以用更少的行完成任务。我希望更有效的重复代码是 processinginstructions 和 processinginstructionsTwo。代码在这里:

import React, { useState, useEffect } from "react";
import { Grid, Container } from "@material-ui/core";
import { navSubMenuStyles } from "./Styles";
import "./stylesheets/NavBar.css";
import NavBar from "./NavBar";
import NavMenuLink from "./stylesheets/NavMenuLink";

function NavBarContent() {
  const pageName = ["HIDDEN-FOR-PRIVACY", "HIDDEN-FOR-PRIVACY"];
  const [content, setContent] = useState();
  const [contenttwo, setContenttwo] = useState();

  async function fetchData() {
    const res = await fetch("HIDDEN-FOR-PRIVACY" + pageName);
    res
      .json()
      .then((res) => {
        setContent(res[0].content.rendered.replace(/(\r\n|\n|\r)/gm, ""));
        setContenttwo(res[1].content.rendered.replace(/(\r\n|\n|\r)/gm, ""));
      })
      .catch((err) => console.log(err));
  }

  useEffect(() => {
    fetchData();
  }, []);

  var HtmlToReact = require("html-to-react");
  var HtmlToReactParser = require("html-to-react").Parser;

  var htmlInput = content;
  var htmlInputTwo = contenttwo;

  // Order matters. Instructions are processed in the order they're defined
  var processNodeDefinitions = new HtmlToReact.ProcessNodeDefinitions(React);
  var processingInstructions = [
    {
      //// subMenus \\// subMenus \\\\
      replaceChildren: true,
      shouldProcessNode: function (node) {
        return node.attribs && node.attribs["data-cat"] === "submenu";
      },
      processNode: function (node, children) {
        return (
          <li className="menu-link">
            {pageName[0]}
            <NavBar children={children} />
          </li>
        );
      },
    },
    {
      // replaceChildren:true,
      shouldProcessNode: function (node) {
        return node.parent && node.parent.name && node.parent.name === "h1";
      },
      processNode: function (node, children) {
        return null;
      },
    },
    {
      // Anything else
      shouldProcessNode: function (node) {
        return true;
      },
      processNode: processNodeDefinitions.processDefaultNode,
    },
  ];

  var processingInstructionsTwo = [
    {
      //// subMenus \\// subMenus \\\\
      replaceChildren: true,
      shouldProcessNode: function (node) {
        return node.attribs && node.attribs["data-cat"] === "submenu";
      },
      processNode: function (node, children) {
        return (
          <li className="menu-link">
            {pageName[1]}
            <NavBar children={children} />
          </li>
        );
      },
    },
    {
      // replaceChildren:true,
      shouldProcessNode: function (node) {
        return node.parent && node.parent.name && node.parent.name === "h1";
      },
      processNode: function (node, children) {
        return null;
      },
    },
    {
      // Anything else
      shouldProcessNode: function (node) {
        return true;
      },
      processNode: processNodeDefinitions.processDefaultNode,
    },
  ];
  var htmlToReactParser = new HtmlToReactParser();
  var reactComponent = htmlToReactParser.parseWithInstructions(
    htmlInput,
    () => true,
    processingInstructions
  );
  var reactComponenttwo = htmlToReactParser.parseWithInstructions(
    htmlInputTwo,
    () => true,
    processingInstructionsTwo
  );

  return (
    <div style={{ backgroundColor: "silver" }}>
      <Container
        style={{
          maxWidth: "1060px",
          width: "100%",
          height: "auto",
          display: "block",
        }}
      >
        <Grid container alignItems="center" style={{ display: "flex" }}>
          <Grid item xs={5}>
            Logo
          </Grid>
          <Grid item xs={7}>
            <nav>
              <ul style={{ display: "flex" }}>
                {reactComponent}
                {reactComponenttwo}
              </ul>
            </nav>
          </Grid>
        </Grid>
      </Container>
    </div>
  );
}

export default NavBarContent;

任何帮助将非常感激。

4

1 回答 1

0

会建议你开始Builder为处理指令创建一个。这将使您可以控制设置的顺序和属性,还可以将构建器扩展到一个库,以便您将来封装一些样板代码。

下面的代码不是一个完整的解决方案,而是作为一个示例,可以解决组织问题并在一定程度上保证指令定义的顺序。

类似于以下内容:

/*
* Setup the processing instructions builder
*/
function processingInstructionsBuilder() {
   var _instructions = [];
}

processingInstructionsBuilder.prototype.end = function() {
   return [...instructions];
};

processingInstructionsBuilder.prototype.newInstructions = function() {
   var builder = new instructionsBuilder(this, (props) => {
      this._instructions.push(props);
   });
   return builder;
};
// other builder functions here...

/*
* Setup the instructions builder
*/
function instructionsBuilder(parent, endCallback) {
   var _parent = parent || null;
   var _endCallback = endCallback || null;
   var _properties = {};
}

instructionsBuilder.prototype.end = function() {
   if (!!_endCallback) {
     _endCallback(_properties);
   }
   return this._parent || this._properties;
};

instructionsBuilder.prototype.canReplaceChildren = function(trueOrFalse) {
   // Some validations here...
   this._properties.replaceChildren = trueOrFalse;
   return this;
};

instructionsBuilder.prototype.shouldProcessNode = function(shouldProcessNodeFunc) {
   // Some validations here...
   this._properties.shouldProcessNode = shouldProcessNodeFunc;
   return this;
};

instructionsBuilder.prototype.processNode = function(processNodeFunc) {
   // Some validations here...
   this._properties.processNode = processNodeFunc;
   return this;
};
// other builder functions here...

一些示例用法...

/*
* Usage...
*/
var builder = new processingInstructionsBuilder();
// Gets an array with processing instructions, in the created order...
var instructions = builder
   .newInstructions(/* instructions 1 */)
      .canReplaceChildren(true)
      .shouldProcessNode(function(node) {
         // some useful code here... 
      })
      .processNode(function (node, children) {
         // some useful code here... 
      })
   .end(/* instructions 1 */)
   .newInstructions(/* instructions 2 */)
      .canReplaceChildren(false)
      .shouldProcessNode(function(node) {
         // some useful code here... 
      })
      .processNode(function (node, children) {
         // some useful code here... 
      })
   .end(/* instructions 2 */)
.end(/* processing instructions builder */);

/*
* Alternative usage...
*/
var builder1 = new instructionsBuilder();
var inst1 = builder1.canReplaceChildren(true)
.shouldProcessNode(function(node) {
   // some useful code here... 
})
.processNode(function (node, children) {
   // some useful code here... 
})
.end(/* instructions 1 */);

var builder2 = new instructionsBuilder();
var inst1 = builder2
.canReplaceChildren(false)
.shouldProcessNode(function(node) {
   // some useful code here... 
})
.processNode(function (node, children) {
   // some useful code here... 
})
.end(/* instructions 2 */);
于 2020-08-08T21:47:01.977 回答