ReactJS:仅当数组有值时才呈现元素

ReactJS : Only render element if array has values

本文关键字:元素 数组 ReactJS      更新时间:2023-09-26

如果数组有值并且存在,我只想将数组值呈现为元素。在我的例子中,有一个颜色数组,用户可以设置当前color_theme,由其索引表示。开始时不应选择color_theme。我的渲染函数将尝试渲染当前color_color_theme,但current_color_index没有。如何在渲染之前检查是否存在现存的彩色血红素?我无法在重新加载之前编写返回,因为还有其他元素必须渲染。

 data = {
   "colorthemes" : [ ["blue","red"], ["black","grey"] ],
   "current_color_index": "", 
   ....//more 
 }

    render: function() {
    return (
        <div>
            <ul>
                //other stuff is rendering
            </ul>
            <ul>
                    {this.state.data.colorthemes[this.state.data.current_color_index].map(function(item, i) {
                      ....
                    }, this)}  
            </ul>
       </div>

只需在jsx内使用 if 条件,例如

{
    condition ?
    <MyRenderElement /> :
    null
}

如果不满足条件,则此代码块不会呈现任何内容。

建议:我建议您使用合理的默认值,而不是使用这样的 if 条件。帮助您保留较少的控制流路径和较少的错误。

我认为你可以用更简单的方式做到这一点,比如:

{ condition && <MyRenderElement/> }

我想说这对你的情况更有意义。