首页 > 解决方案 > TypeError:_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 => {在下面的代码中指明了这行代码。我想知道为什么会这样?

我遇到了这篇带有相关错误的帖子,但在我的上下文中无法弄清楚。

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 { … }

标签: reactjsreact-state

解决方案


如上所示,类型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)

推荐阅读