现在,更改值m
(TheDemo
的状态),组件树的 struct 改变,v
(TheChild
的状态)将重置为初始值3
.
我想要的是:在更改值m
的同时,保持值v
不变.
https://codesandbox.io/s/cool-waterfall-if1v0z?file=/index.js个
import React, { StrictMode, useState } from "react";
import { createRoot } from "react-dom/client";
function TheDemo() {
const [m, setM] = useState(true);
const child = <TheChild />;
return (
<div style={{ fontFamily: "monospace" }}>
<button onClick={() => setM(!m)}>m = {+m}</button>
{m ? <b>{child}</b> : <span>{child}</span>}
</div>
);
}
function TheChild() {
const [v, setV] = useState(3);
return <button onClick={() => setV(v + 1)}>v = {v}</button>;
}
const root = createRoot(document.getElementById("root"));
root.render(
<StrictMode>
<TheDemo />
</StrictMode>
);
也许这是个X-Y问题?原始问题是我想要允许用户更改页面布局,将子代_0从Parent_1移动到Parent_2.
这个演示被简化了,我有很多嵌套的子组件,而提升所有状态几乎是不可能的.
陶渊明的 comments 解决了这个问题,react docs link here.