2015-04-06 87 views
2

我正在創建簡單的應用程序reactjs/flux方式。 我有MessageStoreUserStore包含該數據:在reactjs組件中預加載數據

MessageStore包含

[ 
    {"id": 1, "text": "It is a test message", "userId": 155123} 
] 

UserStore包含

[ 
    {"id": 155123, "name": "Thomas Brown", "age": 35} 
] 

我創建組件來顯示消息。它需要用戶名,但它只有userIdprops獲得。

目前我使用的initial-ajax-like approach得到這個數據(警告:ES6反應語法):

componentDidMount() { 
    var author = UserStore.getById(this.props.userId); 
    this.setState({ 
     author: author 
    }) 
} 
render() { 
    return (<a>{this.state.author.name</a>); 
} 

它是正確的嗎?我發現在這種情況下render功能被稱爲兩次有沒有其他方法可以做到這一點?渲染加載圖標?避免在檢索數據之前進行渲染?

+1

是正確的? 'render'將在初始傳遞期間被調用一次,然後當你更新'狀態'時再被調用。如果您不喜歡這種模式,那麼在創建組件之前,您需要預加載數據**。 – WiredPrairie 2015-04-06 12:40:57

+0

@WiredPrairie在做**之前還包括** getIntitialState **調用? – ivstas 2015-04-06 12:56:39

+0

我建議你不能在通常託管組件的任何容器中創建組件。 – WiredPrairie 2015-04-06 13:48:47

回答

2

每個人都應該移動

var author = UserStore.getById(this.props.userId); 
return({ 
    author: author 
}) 

部分getInitialState生命週期。

對於組件的每個實例,getInitialState只會被調用一次,在這裏您將有機會初始化實例的自定義狀態。與getDefaultProps不同,每次創建實例時都會調用此方法一次。此時你可以訪問this.props。