Answer the question
In order to leave comments, you need to log in
How to safely unmount a component in React?
By clicking on the button in one component, I delete the component in the parent with the following code:
// 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} />
}
}
Answer the question
In order to leave comments, you need to log in
class ComponentA extends React.PureComponent {
state = { isMounted: true };
removeB = () => {
this.setState({ isMounted: false });
};
render() {
const { isMounted } = this.state;
return (
<div>
{isMounted && <ComponentB />}
<ComponentC onClick={this.removeB} />
</div>
);
}
}
It's better to do it like this:
// componentA.jsx
class ComponentA extends React.PureComponent {
state = {
mounted: false
}
removeB = () => {
this.setState({ mounted: !this.state.mounted })
}
render() {
let { mounted } = this.state
return <div>
{
(mounted) ? <ComponentB /> : <ComponentC onClick={this.removeB} />
}
</div>
}
}
// componentB.jsx
class ComponentB extends React.PureComponent {
render() {
return <div>ComponentB</div>
}
}
// componentC.jsx
class ComponentC extends React.PureComponent {
render() {
return <button onClick={this.props.onClick}>ComponentC click me</button>
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question