请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

嵌套函数组件更新阶段似乎不行

用my-mini-ract运行下面的代码,点击FirstChild的Button,会导致整个HTML 只剩下HostRoot

// 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 />) 

正在回答 回答被采纳积分+3

1回答

高少云 2025-04-14 02:04:13

简单的嵌套函数组件更新,已经实现了,你跟着课程视频里写就行。如果再深入,有可能没实现,这毕竟是个学习React的过程,并不是真的要实现一个一模一样的React,所以有些细节没实现也是正常哈~

微信已经回复过这个问题,这里再回复是流程哈,不用再跟进~

0 回复 有任何疑惑可以回复我~
问题已解决,确定采纳
还有疑问,暂不采纳
前端跳槽突围课,React18底层源码深入剖析
  • 参与学习       114    人
  • 解答问题       17    个

从框架使用者蜕变成源码贡献者,助力顺利摆脱就业,跳槽困境

了解课程
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号