问题描述
所以我正在处理一个 tsx 文件,我试图将一些 html 推送到一个变量中,其中的选项从 foreach 项目中获取它们的值,到目前为止一切顺利,但随后我尝试将它们推送到某个数组中并使用它在我的状态下,为了做出正确的反应,它会推动未定义。我很困惑当我尝试将它推入数组时它如何给出 undefined 以及当我尝试将它推入 html 元素时它给出值
provider.getItems().then((items:any[]) => {
items.forEach((item) => {
this.categoryOptItems.push(item.Title);
this.categoryOpts.push(<option value={item.Title}>{item.Title}</option>)
})
this.setState({categories:
this.categoryOptItems
})
})
解决方法
我找到了我的解决方案,但不确定这是否是最好的方法。
这是在 componentDidMount 中
provider.getItems().then((items:any[]) => {
items.forEach((item) => {
categoryOptItems.push(item.Title);
})
this.setState({categories:
categoryOptItems
})
})
这是功能
options() {
var categories = this.state.categories;
const html:any = [];
for (var i = 0; i < this.state.categories.length; i++) {
html.push(<option value={i+1}>{categories[i]}</option>);
}
return html;
}