首页 > 解决方案 > 如何解决 Firefox 上 React.js 中的“this.props.items is undefined”?

问题描述

我为 SelectBox 制作了一个组件。当我使用 axios 以 JSON 格式发送数据时,它在新版本的 Mozilla Firefox 中无法正常工作。在 Chrome、IE 和以前版本的 Firefox 上测试它可以正常工作,但在新版本的 Firefox 中它显示错误“this.props.items is undefined”。谁能指导我如何解决这个问题?

"@babel/polyfill": "^7.4.4",
"axios": "^0.19.0",
"bootstrap": "^4.3.1",
"core-js": "^3.1.4",
"es6-promise-promise": "^1.0.0",
"history": "^4.9.0",
"raf": "^3.4.1",
"react": "^16.8.5",
"react-countdown-clock": "^2.6.0",
"react-dom": "^16.8.5",
"react-router": "^5.0.1",
"react-router-dom": "^5.0.1",
"react-scripts": "2.1.8"

---组件选择框---

class SelectBox extends Component {
  render() {
    return (
      <div>
        <select onChange={this.props.onChange} className={this.props.className}>
          {this.props.items.map(function(item, i) {
            return (
              <option value={item.value} key={i} id={i}>
                {item.name}
              </option>
            );
          })}
        </select>
      </div>
    );
  }
}

---页面我使用这个组件---

class Real extends Component {
  constructor(props) {
    super(props);
    this.state = {
      comboListMonth: [],
      month: "a"
    };
  }

  componentDidMount() {
    axios.get("/month.json").then(response => {
      let ArrItem = [];
      ArrItem.push({ value: "-1", name: "aa" });
      response = response.data;
      for (let i in response) {
        let item = { value: response[i].value, name: response[i].name };
        ArrItem.push(item);
      }
      this.setState({ comboListMonth: ArrItem });
    });
  }
  render() {
    return (
      <SelectBox
        items={this.state.comboListMonth}
        valueSelect={this.state.month}
        id={"combo-2"}
        onChange={this.handleChangeActive()}
      />
    );
  }
}

标签: jsonreactjsfirefoxaxiosmozilla

解决方案


您需要在选项呈现之前添加条件

如果 this.props.items 有数据,则只在选择中呈现选项。

见下面的代码,

<select onChange={this.props.onChange} className={this.props.className}>
      {this.props.items && this.props.items.map(function(item, i) {
        return (
          <option value={item.value} key={i} id={i}>
            {item.name}
          </option>
        );
      })}
    </select>

推荐阅读