2017-06-02 65 views
-1

我正在嘗試創建一個容器,該容器從名爲ProfileCandidate的集合中加載用戶詳細信息。我使用propTypes,我不確定我在做什麼錯誤。我相信這是一個加載順序錯誤,因爲我的propType加載了一個空對象。我知道容器正在運行,因爲它正在訂閱我的profileCandidate.private請求。PropType不填充

路徑:components/ContactDetails.js

class ContactDetails extends React.Component { 
    constructor(props) { 
    super(props); 
    var ProfileCandidate = this.props.profileCandidate; 
    console.log("ProfileCandidate: ", this.props.profileCandidate); 
    }; 
} 

ContactDetails.propTypes = { 
    profileCandidate: React.PropTypes.object.isRequired, 
}; 

export default createContainer(() => { 
    Meteor.subscribe('profileCandidate.private'); 
    var test = ProfileCandidate.findOne({userId: Meteor.userId()}); 
    console.log("test: ", test); 
    return { 
    profileCandidate: ProfileCandidate.findOne({userId: Meteor.userId()}) || {}, 
    }; 
}, ContactDetails) 
+0

你是否試圖渲染視圖?預計組件構建時會得到空對象,因爲發佈沒有時間向客戶端發送數據。不要期望構造函數中的'props'包含只在稍後重新運行容器後纔可用於'render'的數據。 – MasterAM

回答

1

createContainer負載異步數據,所以profileCandidate的初始狀態將是undefined。您可以在createContainer回調中看到您的數據,因爲您在由MeteorDataManager in react-meteor-data line 107創建的執行上下文中,但在此之前ContactDetails使用空的道具呈現。

你應該基於只有當它的加載this.props.profileCandidate做邏輯,所以沒有在costructorrendercomponentDidUpdate方法。

請更改propTypes,以便不再需要該屬性,因爲它將異步加載。請注意,從React v15.5開始已棄用React.PropTypes。請使用prop-types library instead