Cannot read property 'match' of undefined

2019-07-09 02:16发布

I am trying to display some text in React JS frontend in place of a profile image when it isn't available.Basically, I pass the current customer name to a function which extracts the first characters of all the words in the name. I am able to display just the name but when I do a function call, I get Cannot read property 'match' of undefined" error and the page does not render. Console.log() displays undefined.

HTML:

<li className="nav-item">

               <div id="container_acronym">
                 <div id="name_acronym">                        
                    {this.acronym_name(this.state.lead_details.customer_name)}
                 </div>
                </div>                 
        </li>

JS:

acronym_name(str){
var regular_ex=/\b(\w)/g;
var matches = str.match(regular_ex);
var acronym = matches.join('');
document.getElementById("name_acronym").innerHTML = acronym;
}

2条回答
做自己的国王
2楼-- · 2019-07-09 02:41
 acronym_name(str){

        if (typeof str == 'undefined') {   
            str = '';
        }
        else{ 
            var regular_ex=/\b(\w)/g;
            var matches = str.match(regular_ex);
            var acronym = matches.join('');
            return acronym;

        }
    }
查看更多
▲ chillily
3楼-- · 2019-07-09 02:42

this.state.lead_details.customer_name seems undefined, so you need to catch that case.

You have multiple ways of doing this, if you use babel this declaration with default value should work:

acronym_name(str = ''){
    var regular_ex=/\b(\w)/g;
    var matches = str.match(regular_ex);
    var acronym = matches.join('');
    document.getElementById("name_acronym").innerHTML = acronym;
}

Otherwise you can also check inside the function if undefined was given:

acronym_name(str){
    if (typeof str == 'undefined') {
        str = '';
    }
    var regular_ex=/\b(\w)/g;
    var matches = str.match(regular_ex);
    var acronym = matches.join('');
    document.getElementById("name_acronym").innerHTML = acronym;
}

Lastly you could in some way prevent giving undefined to the function in the first place. For example like this:

<li className="nav-item">
    <div id="container_acronym">
        <div id="name_acronym">                        
           {this.acronym_name(this.state.lead_details.customer_name || '')}
        </div>
    </div>                 
</li>
查看更多
登录 后发表回答