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

后端 未结 5 658
臣服心动
臣服心动 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

    In most cases, it is enough just to hide the element, for example in this way:

    export default class ErrorBoxComponent extends React.Component {
        constructor(props) {
            super(props);
    
            this.state = {
                isHidden: false
            }
        }
    
        dismiss() {
            this.setState({
                isHidden: true
            })
        }
    
        render() {
            if (!this.props.error) {
                return null;
            }
    
            return (
                
    { this.props.error } ×
    ); } }

    Or you may render/rerender/not render via parent component like this

    export default class ParentComponent extends React.Component {
        constructor(props) {
            super(props);
    
            this.state = {
                isErrorShown: true
            }
        }
    
        dismiss() {
            this.setState({
                isErrorShown: false
            })
        }
    
        showError() {
            if (this.state.isErrorShown) {
                return 
            }
    
            return null;
        }
    
        render() {
    
            return (
                
    { this.showError() }
    ); } } export default class ErrorBoxComponent extends React.Component { dismiss() { this.props.dismiss(); } render() { if (!this.props.error) { return null; } return (
    { this.props.error } ×
    ); } }

    Finally, there is a way to remove html node, but i really dont know is it a good idea. Maybe someone who knows React from internal will say something about this.

    export default class ErrorBoxComponent extends React.Component {
        dismiss() {
            this.el.remove();
        }
    
        render() {
            if (!this.props.error) {
                return null;
            }
    
            return (
                
    { this.el = el} }> { this.props.error } ×
    ); } }

提交回复
热议问题