React.js:无法读取未定义的属性“ toLowerCase”

时间:2020-03-05 21:10:56

标签: javascript reactjs 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();

2 个答案:

答案 0 :(得分:1)

如果该cookie值不存在,

cookie.load返回undefined。无需天真地将值转换为小写,您需要首先检查它是否存在。例如:

roleCookie = roleCookie ? roleCookie.toLowerCase() : roleCookie;

答案 1 :(得分:0)

对于可能面对undefined的每个数据获取和分配,最好像下面这样根据代码进行回退:

accountId = cookiefetch('accountId','') ? cookiefetch('accountId','') : 'someDefaultValue'

此外,您可以通过条件将其覆盖作为例外

if(accountId) { var accid = accountId.toLowerCase(); }

顺便说一句,不再使用componentWillMount()并使用componentDidMount()。异步就是异步:)