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

时间:2019-09-16 10:01:21

标签: javascript arrays reactjs

我在编译时在标题中得到警告。我了解这与不处理某些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);
        });

  }

2 个答案:

答案 0 :(得分:1)

这是因为您误用了map,该map用于将一个数组映射/转换为另一个数组。调用forEach而没有返回值表示存在问题,因为您不应该使用它来迭代执行某些操作的数组。

您真正想要的是一个binary_crossentropy通话。

答案 1 :(得分:0)

要过滤数组,请使用Array#filter。您也可以在案件中使用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);
    });
}

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
}