2017-08-29 4 views
0

trackercomponentDidMountにあり、notesという名前のコレクション内のアイテムにアクセスしようとしています。しかし、私はconsole.log(doc)を見つけたら、見つけたい文書を返しますが、console.log(doc.likes)は何も返さず、Uncaught TypeError: Cannot read property 'likes' of undefinedのエラーを返します。私がしようとしているのは、ページがロードされ、状態がlikes: doc.likes.lengthに設定されているときです。今はうまくいきますが、すべてのお気に入りを取得するには、配列にlikeを追加する必要があります。ドキュメント内のアイテムにアクセスすると何も返されませんが、ドキュメントを返す

constructor(props){ 
    super(props); 
    this.state = { 
     doc: {}, 
     likes: 0, 
     dislikes: 0 
    }; 
    } 
    componentDidMount() { 
    Meteor.subscribe("notes"); 
    this.tracker = Tracker.autorun(() => { 
     let doc = Notes.findOne(this.props.match.params.noteId); 
     console.log(doc.likes) 
     this.setState({ doc }) 
    }) 
    } 
    componentWillReceiveProps(nextProps) { 
    if(this.props.match.params.noteId != nextProps.match.params.noteId) 
     this.tracker = Tracker.autorun(() => { 
     const doc = Notes.findOne(nextProps.match.params.noteId); 
     console.log(doc.likes) 
     this.setState({ doc }); 
     }) 
    } 
    renderNote(doc){ 
    return(
     <div className="fullSize-container"> 
     <div className="left"> 
      <img className="fullSize-image" src={doc.imageURL} /> 
      <p className="center"> 
      <span onClick={() => { 
       Meteor.call("like", doc._id, doc.userEmail, (err, res) => { 
       this.setState({ likes: res }) 
       }) 
      }}>⬆</span> 
      {this.state.likes} 
      <span onClick={() => { 
       Meteor.call("dislike", doc._id, doc.userEmail, (err, res) => { 
       this.setState({ dislikes: res }) 
       }) 
      }}>⬇</span> 
      {this.state.dislikes} 
      </p> 
     </div> 
     <div className="right"> 
      <h2>{doc.title}</h2> 
      <h3>{doc.userEmail}</h3> 
      <br /> 
      <span className="description">{doc.description}</span> 
     </div> 
     </div> 
    ) 
    } 

    render(){ 
    return (
     <div className="center"> 
     <Menu /> 
     {this.renderNote(this.state.doc)} 
     </div> 
    ) 
    } 

答えて

1

あなたの問題はlikesプロパティではありませんが、あなたのdocundefinedある状況に。あなたはMeteor.subscribe後もすぐにTracker.autorunを使用していて、const doc = Notes.findOne(...)を使用している前に、あなたのnotesコレクションがその文書を取得していないためであろうと

Uncaught TypeError: Cannot read property 'likes' of undefined

:エラーテキストがはっきりと述べています。それを解決する方法は2つあります

[お勧めできません]というサブスクリプションを確保するために、サブスクリプションのonReadyコールバックでコールTracker.autorunは、(コレクションの文書が受信されている)準備ができている:

Meteor.subscribe('notes',() => { 
    this.tracker = Tracker.autorun(...); 
    ... 
}); 

[推奨]docの値を確認してから使用してください。

const doc = Notes.findOne(...); 
if (doc == null) { 
    return; 
} 
... 
+0

最初の解決策が推奨されないのはなぜですか? –

+0

コレクションの 'ready'状態は、ドキュメントが存在することを保証しないので:) – Styx

+0

@StuartFong最も良い方法は、両方のソリューションをマージすることです:) – Styx

関連する問題