foreach 中的值是否推送未定义?

问题描述

所以我正在处理一个 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;        
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...