类型错误:_this2.props.value.forEach 不是函数

问题描述

加载以下组件时出现以下错误

TypeError: _this2.props.value.forEach is not a function
    fetchRecords webpack:///./src/main/js/components/forms/AutoCompanies.js?:122
    promise callback*fetchRecords webpack:///./src/main/js/components/forms/AutoCompanies.js?:115
    componentDidMount webpack:///./src/main/js/components/forms/AutoCompanies.js?:149
    React 6
    unstable_runWithPriority webpack:///./node_modules/scheduler/cjs/scheduler.development.js?:653
    React 5
    unstable_runWithPriority webpack:///./node_modules/scheduler/cjs/scheduler.development.js?:653
    React 6
AutoCompanies.js:143:24

而且基本上就是在下面的代码中指明了这行代码 this.props.value.forEach(e => {。我想知道为什么会这样?

我通过 related error 看到了这篇帖子,但无法在我的上下文中弄清楚。

import { Select as CompanySelect } from "react-select-virtualized";

function escapeRegexCharacters(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");
}

const override = css`
  display: block;
  margin: 0 auto;
  border-color: red;
`;

export class AutoCompanies extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: "",selectedCompanyValues: null,selectedCompanies: [],loading: false,};

    this.onChange = this.onChange.bind(this);
    this.companyTemplate = this.companyTemplate.bind(this);
    this.selectedCompaniestemplate = this.selectedCompaniestemplate.bind(this);
  }

  companyTemplate(option) {
    return (
      <div className="country-item">
        <div>{option.label}</div>
      </div>
    );
  }

  selectedCompaniestemplate(option) {
    if (option) {
      return (
        <div className="country-item country-item-value">
          <div>{option.title}</div>
        </div>
      );
    }

    return "Select Companies";
  }

  onChange = (val) => {
    this.setState({
      value: val,selectedCompanyValues: val,});
    this.props.onChange(val);
  };

  fetchRecords() {
    const loggedInUser = JSON.parse(sessionStorage.getItem("loggedInUser"));
    let url = isAdmin(loggedInUser) ? "url1" : "url2?value=" + loggedInUser.id;

    return axios
      .get(url)
      .then((response) => {
        let selectedCompanies = [
          {
            title: "test",label: this.props.value[0] && this.props.value[0].title,},];
        if (this.props.value) {
          this.props.value.forEach((e) => {
            selectedCompanies.push(
              response.data._embedded.companySets.filter((companySet) => {
                return companySet.companySetId === e.companySetId;
              })[0]
            );
          });
        }

        this.setState({
          selectedCompanies: response.data._embedded.companySets.map(
            (item) => ({
              label: item.title,title: item.title,companySetId: item.companySetId,})
          ),selectedCompanyValues: selectedCompanies,});
      })
      .catch((err) => console.log(err));
  }

  componentDidMount() {
    this.fetchRecords(0);
  }

  render() {
    return (
      <div>
        <CompanySelect
          value={this.state.selectedCompanyValues}
          options={this.state.selectedCompanies}
          onChange={this.onChange}
          optionHeight={60}
        />
      </div>
    );
  }
}

编辑:

添加了更多信息:

所以我在代码中的 super(props) 正下方添加了以下语句

 console.log("Props Testing");
        console.log(props);

它打印成这样:

Object { fieldName: "companySets",value: 32714,onChange: onChange(ev)
 }
​
fieldName: "companySets"
​
onChange: function onChange(ev)
​
value: 32714
​
<prototype>: Object { … }

有时,它以数组的形式出现:

 Object { fieldName: "companySets",value: (1) […],onChange: onChange(ev)
 }
​
fieldName: "companySets"
​
onChange: function onChange(ev)​
value: Array [ {…} ]
​​
0: Object { companySetId: 32798,sourceSystem: "12",status: "CONSENTED",… }
​​
length: 1
​​
<prototype>: Array []
​
<prototype>: Object { … }

解决方法

如上所示,value 的类型是一个数字 (32714)。我不知道您要在代码中确切地完成什么,但是修复错误的解决方法是在 if 语句中包含以下内容:

编辑: 由于您希望能够在 value 类型为数字或数组时运行这两种代码,因此您可以这样做:

if (typeof this.props.value === 'number') {
    // Enter your code to run when this.props.value is a number
} else if (Array.isArray(this.props.value)) {
    // Enter your code to run when this.props.value is an array
}

代替

if (this.props.value)