问题:
在下面的代码中,当Toggle ParentA/B
单击按钮时,<Child />
组件将被卸载并再次重新安装,但实际上只有Parent
组件发生了变化。
Child
在这种情况下如何防止卸载和重新安装?
import React, { useState } from "react"
const App = () => {
const [a, setA] = useState(true)
return (
<div>
<button onClick={() => setA(!a)}>Toggle ParentA/B</button>
{a ? <ParentA><Child /></ParentA> : <ParentB><Child /></ParentB>}
</div>
)
}
const ParentA = ({ children }) => <div>parentA{children}</div>
const ParentB = ({ children }) => <div>parentB{children}</div>
class Child extends React.Component {
componentDidMount() {
console.log('child did mount')
}
componentWillUnmount() {
console.log('child will unmount')
}
render() {
return (
<div>child</div>
)
}
}
export default App
对潜在答案的回复:
为什么不让 Child 组件重新挂载,因为它只是一个
<div>
元素?
通常,如果Child
组件的渲染成本低,这无关紧要。但是,在我的情况下,Child
组件需要很长时间才能安装,因此每次Parent
组件更改时我都无法重新安装。
您可以将
parentA
orparentB
字符串作为props传递给通用父组件。
const App = () => {
const [a, setA] = useState(true)
return (
<div>
<button onClick={() => setA(!a)}>Toggle ParentA/B</button>
<ParentGeneric content={a? 'parentA': 'parentB'}><Child /></ParentGeneric>
</div>
)
}
const ParentGeneric = ({children, content}) => <div>{content}{children}</div>
class Child extends React.Component {
...
}
这会奏效。不幸的是,这限制了我的Parent
组件的 JSX 结构是相同的。换句话说,如果 myParentA
和ParentB
的 JSX 结构不同,那么我不确定如何将差异作为props传递。
例如:
const ParentA = ({ children }) => <div><div><h1>parentA{children}</h1></div></div>
const ParentB = ({ children }) => <div>parentB{children}</div>
如果这样定义 parentA 和 parentB,是否仍然可以将这两个组件抽象为一个ParentGeneric
组件并简单地将ParentA
和之间的结构差异ParentB
作为props传递?