2017-07-24 125 views
1

我學流星,我使用它與反應,我試圖做一個strawpoll應用程序,但我有一個問題,當我想呈現一個strawpoll更新渲染和反應

這裏我的組件爲我StrawpollVote觀點:

export default class StrawpollVote extends React.Component{ 
    constructor(props) { 
    super(props); 
    Tracker.autorun(() => { 
     this.strawpoll = Strawpolls.findOne({ "_id": this.props.match.params.id }); 
     this.render(); 
    }); 
    } 

    render(){ 
    if (this.strawpoll) { 
     console.log('strawpoll'); 
     return (
     <p>Strawpoll : {this.strawpoll.title}</p> 
    ); 
    } else { 
     return (
     <p>Strawpoll not found</p> 
    ); 
    } 
    } 
} 

我收到的ID與路線,我覺得strawpoll助理,然後我重新運行的渲染功能,這一切都在Tracker.autorun聽上的變化,但是當我加載的頁面顯示的視圖,其中Strawpoll not found而我的控制檯,我可以看到strawpoll從渲染功能

它只適用於我在自動運行功能上使用this.forceUpdate(),但這會導致警告,爲什麼渲染不會更新視圖?我錯過了什麼嗎?

+0

你在這裏錯過了很多東西。 'render'函數只返回一個html元素,它不會替換當前的DOM。您應該*從不*手動調用'render'函數。相反,使用'createContainer'將Meteor集合轉換爲React道具。看看官方的Meteor教程或這個[小例子](https://stackoverflow.com/documentation/meteor/3121/meteor-react/15114/displaying-a-mongodb-collection#t=201707242227411539265)。 – aedm

回答

0

我已經更新了你的代碼。希望這可以幫助:

export default class StrawpollVote extends React.Component{ 
    constructor(props) { 
    super(props); 

    this.state = {strawpoll: null}; 
    let context = this; 

    Tracker.autorun(() => { 
     let tem = Strawpolls.findOne({ "_id": context.props.match.params.id }); 
     context.setState({strawpoll: tem}); 
    }); 
    } 

    render(){ 
    if (this.state.strawpoll) { 
     console.log('strawpoll'); 
     return (
     <p>Strawpoll : {this.state.strawpoll.title}</p> 
    ); 
    } else { 
     return (
     <p>Strawpoll not found</p> 
    ); 
    } 
    } 
} 

變化:在你的代碼中使用thisTraacker塊內,這不是持有strawpoll實際的上下文。我已經把strawpoll陳述了,因爲更新狀態會自動重新渲染組件,不需要強制渲染!