5
这个例子里的 component 总是重新挂载
source link: https://www.v2ex.com/t/893491
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
const Main = (props)=>{
var [somevar, setSomevar] = useState<number>(0);
const SubComponent = (props)=>{
var [count, setCount] = useState<number>(0);
useEffect(()=>{
console.log("SubComponent mounted!");
return ()=>{console.log("SubComponent dis mounted");};
}, [props]);
return (<div>
<div>count:{count}</div>
<button onClick={()=>setCount(count+1)}>count++</button>
</div>);
}
return (<div>
<div>somevar:{somevar}</div>
<button onClick={()=>setSomevar(somevar+1)}>somevar++</button>
<SubComponent>
</SubComponent>
</div>);
}
每次点击 somevar++,SubComponent 都会重新 mount 和 unmount ,而且 count 也会清零。 点击 count++不会导致重新挂载。
什么决定了重新挂载呢?这里的父子组件结构,并没有变化啊。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK