Reactjs 如何在React中安全卸载组件?
通过单击一个组件中的按钮,我删除了父组件中的组件,代码如下:Reactjs 如何在React中安全卸载组件?,reactjs,Reactjs,通过单击一个组件中的按钮,我删除了父组件中的组件,代码如下: // componentA.jsx class ComponentA extends React.PureComponent { removeB() { this.setState({ mounted: false }) } renderB() { if (!this.state.mounted) { return null } return <ComponentB /&
// componentA.jsx
class ComponentA extends React.PureComponent {
removeB() {
this.setState({ mounted: false })
}
renderB() {
if (!this.state.mounted) {
return null
}
return <ComponentB />
}
render() {
return <div>
{this.renderB()}
<ComponentC onClick={this.removeB} />
</div>
}
}
// componentB.jsx
class ComponentB extends React.PureComponent {
render() {
return ...
}
}
// componentC.jsx
class ComponentC extends React.PureComponent {
render() {
return <Button onClick={this.props.onClick} />
}
}
//组件a.jsx
类ComponentA扩展了React.PureComponent{
removeB(){
this.setState({mounted:false})
}
renderB(){
如果(!this.state.mounted){
返回空
}
返回
}
render(){
返回
{this.renderB()}
}
}
//组件b.jsx
类ComponentB扩展了React.PureComponent{
render(){
返回。。。
}
}
//组件c.jsx
类ComponentC扩展了React.PureComponent{
render(){
返回
}
}
我得到一个错误:
未能在“节点”上执行“removeChild”:要删除的节点不是此节点的子节点
您的问题是因为函数
removeB
中的此变量引用了错误的范围(在您的示例中,ComponentC
的范围,它应该引用正确的范围,即ComponentA
)
在传递事件处理程序之前,应将其正确绑定到ComponentA
的范围
您可以通过以下两种方式实现:
class ComponentA extends React.PureComponent {
constructor() {
this.removeB = this.removeB.bind(this); // Bind event handlers in constructor
}
removeB() {
this.setState({ mounted: false })
}
....
render() {
return <div>
{this.renderB()}
<ComponentC onClick={this.removeB} />
</div>
}
}
class ComponentA扩展了React.PureComponent{
构造函数(){
this.removeB=this.removeB.bind(this);//构造函数中的绑定事件处理程序
}
removeB(){
this.setState({mounted:false})
}
....
render(){
返回
{this.renderB()}
}
}
或:
class ComponentA扩展了React.PureComponent{
removeB=()=>{
this.setState({mounted:false})
}//使用arrow函数将函数绑定到当前词法作用域
....
render(){
返回
{this.renderB()}
}
}
您可以在此处阅读有关JS词法范围的更多信息:
此外,React文档中提到的将事件处理程序绑定到正确的作用域:
class ComponentA extends React.PureComponent {
removeB = () => {
this.setState({ mounted: false })
} // Using arrow function to bind function to the current lexical scoping
....
render() {
return <div>
{this.renderB()}
<ComponentC onClick={this.removeB} />
</div>
}
}