json - 如何解决 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()}
/>
);
}
}
解决方案
您需要在选项呈现之前添加条件
如果 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>
推荐阅读
- javascript - 如何使用 Typescript 使固定的 Promises 数组中的项目成为可选
- python - 在 Python 中使用 dat 文件
- android - 不显示多个项目类型的 Recyclerview
- python - 改进 EfficientNet 的结果
- c++ - 将函数作为参数传递 C++ 时出错
- typescript - 使用打字稿时对象中的未定义属性
- python - ShareDirectoryClient - 检查 Azure 文件共享目录是否存在于 python 中的方法
- c# - 如何在 C# 中将我的“1”更改为“句点”?
- xcode - 在 Xcode 12.5 中打开 Xcode 13.0 项目
- verilog - 如何在生成块内生成 N 个计数器以对 FPGA 进行负载测试?