简体   繁体   English

预期在react中的箭头函数末尾返回一个值

[英]Expected to return a value at the end of arrow function in react

I get the warning in the title when compiling. 编译时,标题中显示警告。 I understand that it is about not handling some cases of if , but how can I filter before mapping in the correct way? 我知道这是关于不处理if某些情况,但是如何在映射之前以正确的方式进行过滤?

    componentDidMount() {
        this.props.UserReducer.user.employeeInfoList.map(role => {
          if (role.employeeType) this.rolesOfUser.push(role.employeeType);

          if (role.xdockId) this.xdockIdsOfUser.push(role.xdockId);
        });

  }

It is because you are misusing map which is used for mapping/transforming one array to another. 这是因为您滥用了用于将一个数组映射/转换为另一个数组的map Having a call to map without a return value indicates a problem, as you shouldn't be using it to just iterate over an array performing some action. 调用不带返回值的map表示一个问题,因为您不应该使用它来迭代执行某些操作的数组。

It looks like what you really wanted was a forEach call. 看来您真正想要的是一个forEach调用。

To filter an array use Array#filter . 要过滤数组,请使用Array#filter Also you can use Array#forEach for your case 您也可以针对您的情况使用Array#forEach

componentDidMount() {
    this.props.UserReducer.user.employeeInfoList.forEach(role => {
      if (role.employeeType) this.rolesOfUser.push(role.employeeType);

      if (role.xdockId) this.xdockIdsOfUser.push(role.xdockId);
    });
}

Or 要么

componentDidMount() {
  const rolesOfUser = this.props.UserReducer.user.employeeInfoList.filter(role => {
    return role.employeeType;
  })

  const xdockIdsOfUser = this.props.UserReducer.user.employeeInfoList.filter(role => {
    return role.xdockId;
  })

  // Do smth with both arrays
}


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM