Cannot read property 'match' of undefined error

二次信任 提交于 2019-12-10 23:48:05

问题


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;
}

回答1:


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>



回答2:


 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;

        }
    }


来源:https://stackoverflow.com/questions/49175265/cannot-read-property-match-of-undefined-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!