反应:当useState更改时,为什么这些组件没有更新? (安装应用程序后呈现的组件)

一旦安装了应用程序,就会呈现这些组件(原因是因为这些组件需要插入到获取的纯HTML中)

我看到状态已更改,但是元素对此没有反应

有什么解决办法吗?

codesandbox

import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom";

export default function App() {
  const [elements, setElements] = useState("none");

  useEffect(() => {
    console.log("global useEffect: " + elements);
  }, [elements]);

  const Input = ({ setElements }) => (
    <>
      <input
        type="text"
        onChange={e => {
          setElements(e.target.value);
        }}
      />
      <div>{elements}</div>
    </>
  );
  const Elements = ({ elements }) => {
    useEffect(() => {
      console.log("Elements useEffect: " + elements);
    }, [elements]);
    return <span>{elements}</span>;
  };
  const Elements2 = ({ elements }) => <span>{elements}</span>;

  useEffect(() => {
    console.log("useEffect first time");
    ReactDOM.render(
      <Elements elements={elements} />,
      document.getElementById("elements")
    );
    ReactDOM.render(
      <Elements2 elements={elements} />,
      document.getElementById("elements2")
    );
    ReactDOM.render(
      <Input setElements={setElements} />,
      document.getElementById("inputId")
    );
  }, []);

  // need to split plainhtml, otherwise codesandbox
  // ...gives an error that is IMO a bug
  const plainhtml1 = `
  <div>
  <div>This plain html has been fetched</div>
  <div id="inputId" />
  </div>
  `;
  const plainhtml2 = `
  <div>
  <div>number of elements:</div>
  <div id="elements" />
  </div>
  `;
  const plainhtml3 = `
  <div>
  <div>number of other elements:</div>
  <div id="elements2" />
  </div>
  `;

  return (
    <div>
      <h1>Hello CodeSandbox</h1>
      <div dangerouslySetInnerHTML={{ __html: plainhtml1 }} />
      <div dangerouslySetInnerHTML={{ __html: plainhtml2 }} />
      <div dangerouslySetInnerHTML={{ __html: plainhtml3 }} />
    </div>
  );
}
评论