簡體   English   中英

當我調用 React.useState() 返回的更新 function 時會發生什么?

[英]What happens when I call the update function returned by React.useState()?

我剛剛學習了 react 中的鈎子,所以我用它寫了一個小功能,當用戶點擊超鏈接時會顯示隱藏的文本。 我終於使代碼工作了,但似乎我的代碼搞砸了。 有人可以告訴我:

  1. 為什么“true”在控制台中打印了兩次,當我調用 React.useState() 返回的更新 function 時確實發生了什么? 如何改進我的代碼以防止這種情況發生?
  2. 如何清楚地將屬性傳遞給功能性 React 組件? 看來我的方法真的很復雜(壓縮在一個屬性對象中)。

這是功能:點擊前點擊

這是我的代碼:

/*
    params:
    attributes: {
        // Required params
        text: the text using the style of hiddenTextLinks with each part separated by a '#'. 
        Ex: "Hey, here is the #HiddenTextLinks#, a wonderful style for texts#!"
        
        // Optional params
        plainStyle: customized style for plain contents.
        plainFont: customized font for plain content (no use if plainStyle is specified).
        plainColor: customized font for plain text color (no use if plainStyle is specified).

        linkStyle: customized style for link contents. 
            Notice: the link here is indeed a button styled as a "link". Therefore, I suggest you to provide 
            the following attributes:
                background: "none",
                border: "none",
                padding: 0,
                textDecoration: "none",
                fontSize: "16px",
        linkFont: customized font for links (no use if linkStyle is specified).
        linkColor: customized font for link color (no use if linkStyle is specified).
        
        hiddenStyle: customized style for hidden texts.
        hiddenFont: customized font for hidden texts. (no use if hiddenStyle is specified).
        hiddenColor: customized color for hidden texts. (no use if hiddenStyle is specified).
    }
*/
function HiddenTextLinks(props) {
  console.log("runned");
  props = props.attributes;
  var text = props.text;
  const plainStyle = props.plainStyle || {
    fontFamily: props.plainFont || "arial, sans-serif",
    color: props.plainColor || "#000000",
  };
  const linkStyle = props.linkStyle || {
    background: "none",
    border: "none",
    padding: 0,
    fontSize: "16px",
    textDecoration: "none",
    fontFamily: props.linkFont || "arial, sans-serif",
    color: props.linkColor || "#000000",
    cursor: "pointer",
  };
  const hiddenStyle = props.hiddenStyle || {
    position: "relative",
    fontFamily: props.hiddenFont || "arial, sans-serif",
    color: props.hiddenColor || "#9e9a9a",
  };
  const [temp] = React.useState(text.split(/(?<!\\)#/));
  const [visibility, setVisibility] = React.useState(
    Array(Math.floor(temp.length / 3)).fill(false)
  );
  const [renderedContent, setRenderedContent] = React.useState(render(temp));

  function render(array) {
    console.log("render");
    return array.map((value, index) => {
      if (index % 3 === 0) {
        return (
          <span key={`content${Math.floor(index / 3)}`} style={plainStyle}>
            {value}
          </span>
        );
      } else if (index % 3 === 1) {
        return (
          <button
            key={`link${Math.floor(index / 3)}`}
            style={linkStyle}
            onClick={() => setVisible(Math.floor(index / 3))}
          >
            {value}
          </button>
        );
      } else {
        console.log(visibility[Math.floor(index / 3)]);
        if (visibility[Math.floor(index / 3)]) {
          return (
            <span key={`hidden${Math.floor(index / 3)}`} style={hiddenStyle}>
              {value}
            </span>
          );
        } else {
          return <span key={`hidden${Math.floor(index / 3)}`}></span>;
        }
      }
    });
  }

  function setVisible(index) {
    visibility[index] = !visibility[index];
    setVisibility(visibility);
    setRenderedContent(render(temp));
  }
  console.log("returned");
  return <span>{renderedContent}</span>;
}

這就是我在上層使用它的方式:

const attributes = {
      text: "Hey, here is the #HiddenTextLinks#, a wonderful style for texts#!",
      plainFont: "Bakbak One, cursive",
      linkFont: "Bakbak One, cursive",
      hiddenFont: "Bakbak One, cursive",
      linkColor: "#d1519c",
      hiddenColor: "#9e9a9a",
    };
return <HiddenTextLinks attributes={attributes} />;

這是控制台日志(我只點擊了一次):控制台日志

太感謝了。

每次組件更新以下行時,您的render() function 都會運行:

const [renderedContent, setRenderedContent] = React.useState(render(temp));

您可以通過傳遞值生成 function 而不是值本身來修復它:

const [renderedContent, setRenderedContent] = React.useState(() => render(temp));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM