[英]ReactJS : Only render element if array has values
我只想將數組值呈現為元素(如果數組具有值並且存在)。 在我的情況下,有一個顏色數組,用戶可以設置當前的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/> }
我要說的是,這對您的情況來說更有意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.