react componentDidMount not firing

前端 未结 9 983
南方客
南方客 2020-12-15 14:47

I set up a new react project and for some reason, the componentDidMount method is not being called.

I have verified this behavior by placing a call to

9条回答
  •  北荒
    北荒 (楼主)
    2020-12-15 15:39

    In my case, I call componentDidMount() for retrieving data from a service (API call) and on the render function I have components that are supposed to use the data that is returned from this call.

    But because the call is Async the render() function is called immediately and then it crashes (many errors like: "TypeError:cannot read property 'XXXX' of undefined" ) then it looks like componentDidMount is not called at all.

    To solve this issue I check on render that myData !== null before returning the component itself - You can use generic loader\spinner on this case that will not render internal components that use data before the data that actually retrieve from service.

    Example:

    componentDidMount() {
        const { GetMyDataFromServiceFunc } = this.props;
    
        GetMyDataFromServiceFunc ("150288");
    }
    
    render() {
        const { details, loading } = this.props;
        
        if (!details)
            return ();
            
            return (
    
            
    
                     
    
                    
                
            
            );
        }
    }
    

提交回复
热议问题