2017-06-15 65 views
-1

說我將total_counts從父項傳遞給子組件。解構和在反應組件中使用道具

在我的孩子們組成部分我有一個渲染方法

render() { 
    console.log(this.props.pagination.total_counts) 
} 

如何使用正確共有TOTAL_COUNTS沒有錯誤?我的兒童渲染方法可能會多次渲染,因爲分頁是通過http調用來完成的。如果我desctructring像下面

const { total_counts } = this.props.pagination 
render(){ 
    return (
     <div>{total_counts && <p>{total_counts.toString()}</p>}</div> 
    ) 
} 

我還是要檢查共有TOTAL_COUNTS不是未定義

+0

你的問題是什麼呢? –

+1

嘗試'const {total_counts} = this.props.pagination'? –

+0

@ D-reaper如果'this.props.pagination'未定義,我的應用會中斷,如果我嘗試呈現total_counts? –

回答

1

如果從this.props.pagination訪問total_counts,那麼解構的說法應該是這樣的:

const { total_counts } = this.props.pagination; 

這假定分頁永遠不會被定義。否則,我建議你先檢查它,如果它不存在則回退到某個值;

// default value if this.props.pagination is undefined 
 
let total_counts = 0; 
 

 
// if this.props.pagination and total_counts property in it exist 
 
// then assign total_counts variable 
 
if (this.props.pagination && this.props.pagination.total_counts) { 
 
    total_counts = this.props.pagination.total_counts; 
 
}

+0

如果this.props.pagination未定義,那麼如果我嘗試呈現total_counts,我的應用會中斷嗎? –

+0

這很可能會。所以,你必須先檢查它是否是第一個未定義的,如果是,則返回到某個值。 –