How to unmount, unrender or remove a component, from itself in a React/Redux/Typescript notification message

后端 未结 5 672
臣服心动
臣服心动 2020-12-02 06:44

I know this question has been asked a couple of times already but most of the time, the solution is to handle this in the parent, as the flow of responsibility is only desce

5条回答
  •  广开言路
    2020-12-02 06:49

    This isn't appropriate in all situations but you can conditionally return false inside the component itself if a certain criteria is or isn't met.

    It doesn't unmount the component, but it removes all rendered content. This would only be bad, in my mind, if you have event listeners in the component that should be removed when the component is no longer needed.

    import React, { Component } from 'react';
    
    export default class MyComponent extends Component {
        constructor(props) {
            super(props);
    
            this.state = {
                hideComponent: false
            }
        }
    
        closeThis = () => {
            this.setState(prevState => ({
                hideComponent: !prevState.hideComponent
            })
        });
    
        render() {
            if (this.state.hideComponent === true) {return false;}
    
            return (
                
    this.closeThis}> YOUR CODE HERE
    ); } }

提交回复
热议问题