![](/img/trans.png)
[英]TypeError: Cannot read property 'toLowerCase' of undefined in react
[英]React.js : Cannot read property 'toLowerCase' of undefined
此錯誤導致整個頁面無法顯示。 我必須在本地加載一個項目(我沒有寫),但這是控制台中彈出的第一件事。
代碼:
class Panel extends React.Component {
constructor(props) {
super(props);
this.state = {
DropdownTitle: 'Screen',
setScreenByCookie: true
};
}
componentWillMount() {
const { dispatch } = this.props;
var roleCookie = cookie.load('role');
roleCookie = roleCookie.toLowerCase();
const accountId = cookiefetch('accountId','');
var accid = accountId.toLowerCase();
const overrideCompany = cookiefetch('overrideCompany', '');
if(overrideCompany != '') {
var title = "Screen ("+overrideCompany+")";
this.setState({DropdownTitle: title});
} else {
this.setState({DropdownTitle: 'Screen'});
}
var roleCookie = roleCookie.toLowerCase();
if (roleCookie == 'administrator' || roleCookie == "adminread") {
dispatch(getCompaniesDropdown());
} else {
dispatch(getCompany(accid));
dispatch(getDropdown(accid));
//dispatch(companyDropdownAction(false, accid, accid));
}
}
錯誤:
Panel.js:47 Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
at Panel.componentWillMount (Panel.js:47)
at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:210)
at ReactCompositeComponentWrapper.ReactCompositeComponent_mountComponent [as mountComponent] (ReactPerf.js:66)
at Object.mountComponent (ReactReconciler.js:37)
at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:225)
at ReactCompositeComponentWrapper.ReactCompositeComponent_mountComponent [as mountComponent] (ReactPerf.js:66)
at Object.mountComponent (ReactReconciler.js:37)
at ReactDOMComponent.mountChildren (ReactMultiChild.js:241)
at ReactDOMComponent._createContentMarkup (ReactDOMComponent.js:591)
at ReactDOMComponent.mountComponent (ReactDOMComponent.js:479)
第 47 行是 toLowerCase 的第一次使用: roleCookie = roleCookie.toLowerCase();
如果該 cookie 值不存在, cookie.load
將返回undefined
。 您需要先檢查它是否存在,而不是天真地將值轉換為小寫。 例如:
roleCookie = roleCookie ? roleCookie.toLowerCase() : roleCookie;
對於可能面臨undefined
每個數據獲取和分配,您最好像下面那樣根據您的代碼進行回退:
accountId = cookiefetch('accountId','') ? cookiefetch('accountId','') : 'someDefaultValue'
您也可以例外通過條件覆蓋它
if(accountId) { var accid = accountId.toLowerCase(); }
順便說一句,不要再使用componentWillMount()
並使用componentDidMount()
。 異步就是異步 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.