Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

嵌套式组件更新出现错误。 #4

Open
itisvincent opened this issue Feb 15, 2025 · 0 comments
Open

嵌套式组件更新出现错误。 #4

itisvincent opened this issue Feb 15, 2025 · 0 comments

Comments

@itisvincent
Copy link

如果是以下这种嵌套的函数组件,
Init load是可以,但如果我点击FirstChild 的button就会出现只余下div的情况,似乎就不能够正确更新

// Second child component that will be passed as props
function SecondChild({ message }: { message: string }) {
  console.log("SecondChild render");
  return (
    <div className="border p-4">
      <h3>Second Child</h3>
      <p>{message}</p>
    </div>
  );
}

// First child component that receives SecondChild as props
function FirstChild({ children }: { children: React.ReactNode }) {
  const [counter, setCounter] = useState(0);
  console.log("FirstChild render, count:", counter); // Add this
  console.log("FirstChild render");
  return (
    <div className="border p-4">
      <h2>First Child</h2>
      <button
        className="px-4 py-2 bg-blue-500 text-white rounded"
        onClick={() => setCounter(prev => prev + 1)}
      >
        Update Counter: {counter}
      </button>
      {children}
    </div>
  );
}

function FunctionComponent() {
  const [count, setCount] = useReducer((x) => x + 1, 0);
  const [text, setText] = useState("hello");

  const deferredText = useDeferredValue(text);

  return (
    <div className="border">
      <h1>函数组件</h1>
      <button
        onClick={(e) => {
          setCount();
        }}
      >
        {count}
      </button>

      <input
        value={text}
        onChange={(e) => {
          setText(e.target.value);
        }}
      />
      <p>{text}</p>

      {/* 非紧急更新 */}
      <b>{deferredText}</b>
      {/* <MySlowList text={deferredText} /> */}

      {/* Added nested children components */}
      <FirstChild>
        <SecondChild message="Hello from Second Child!" />
      </FirstChild>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
  (<FunctionComponent />) as any
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant