React渲染的時候採坑記,一定要return給render

React採坑記
今天在用策略模式改寫代碼的時候,本來想簡化一下代碼,將渲染組件抽離出去,不料踩了一個小坑。
雖然在函數裏返回了內容,但是render()也是一個函數,所以也需要return內容
原代碼如下:

<div id='wrapper'>         
{                
	this.props.data.map((item, index) => {
	if (item.template === 'grid' && this.props.reportDataList[item.code]) {//做一下限制,保證子組件裏都有數據 
		 return (
		      <div></div>
		 )
	}                           
	if (item.template === 'trend') {
		return (
		   <div></div>                                            
		)
	} 
	....                             
}
</div>

這裏想把原來的if條件裏的div抽離出去,改成策略模式,通過函數返回
// 錯誤寫法

getContent = ()=>{
	return <div></div>
}
<div id='wrapper'>         
{                
	this.props.data.map((item, index) => {
	if (item.template === 'grid' && this.props.reportDataList[item.code]) {//做一下限制,保證子組件裏都有數據 
	 	this.getContent();
	}                           
	if (item.template === 'trend') {
		this.getContent(); 
	}
	....                             
}
</div>

正確的改進:

getContent = ()=>{
	return <div></div>
}
<div id='wrapper'>         
{                
	this.props.data.map((item, index) => {
	if (item.template === 'grid' && this.props.reportDataList[item.code]) {//做一下限制,保證子組件裏都有數據 
	 	return this.getContent();
	}                           
	if (item.template === 'trend') {
		return this.getContent(); 
	}
	....                             
}
</div>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章