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

React: Why are these components not updated when useState changes? (components rendered after the app is mounted)

组件在安装应用程序后呈现(原因是因为这些组件需要插入到获取的普通 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>
  );
}

元素不知道 App 状态在发生变化时发生变化。通过使用这样的效果告诉他们这些变化:

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

React 将在每次 elementssetElements 值更改时调用效果(并因此重新渲染元素)。实际上,因为你有一个非常相似的效果,你只需要添加 elements 到它的依赖列表(第二个参数中的数组)。