2017-11-10 9 views
1

ステートフルな子コンポーネント内の親オブジェクトにアクセスしようとしていますが、オブジェクトが見つからない理由を理解できないようです。このコンポーネントはステートレスから変換されて正常に機能していたので、変換後に何が壊れたのか不思議です。状態内に空の配列を設定し、次に小道具でsetStateする関数を設定する必要がありますか?ここでステートフルな子コンポーネントで小道具にアクセスする

は誤りです:あなたは間違った行でエラーを発見

//GET /api/app and set to state 
class BlogFeedContainer extends React.Component{ 
    constructor(props, context) { 
     super(props, context); 
     this.state = this.context.data || window.__INITIAL_STATE__ || {blogs: []}; 
    } 

    fetchList() { 
     fetch('http://localhost:3000/api/test') 
      .then(res => { 
       return res.json(); 
      }) 
      .then(data => { 
       console.log(data); 
       this.setState({ blogs: data.blog, user: data.user, csrf: data.csrfToken }); 
      }) 
      .catch(err => { 
       console.log(err); 
      }); 
    } 

    componentDidMount() { 
     this.fetchList(); 
    } 

    render() { 
     return (
      <div className="container"> 
       <h2>Comments List</h2> 
       <BlogFeed {...this.state} /> 
      </div> 
     ) 
    } 
}; 

//Loop through JSON and create Blog and Comment Container Component 
class BlogFeed extends React.Component { 
    constructor(props){ 
     super(props); 
     this.state = { 
      comments: [] 
     }; 
    } 

    render(){ 
     return (
      <div> 
      { 
       this.props.blogs.map((blog, index) => { 
        return (
         <div className="row"> 
          <div className="col-md-6 col-md-offset-3 blog-card"> 
           <BlogCard {...blog} key={blog.blogIdHash} user={props.user} /> 
           <Comments {...blog} key={index} blogId={blog.blogIdHash} csrf={props.csrf}/> 
          </div> 
         </div> 
        ); 
       }) 
      } 
      </div> 
     ); 
    } 
} 
+0

はどのような状態には見えますか? 'console.log(this.state)'の出力は何ですか? – mersocarlin

+1

JSXを返す前に 'blogFeed'コンポーネントのレンダリングでそのconsole.logを設定すると、空のコメント配列を持つオブジェクトが表示されます – cphill

答えて

2

:ここではラインで

Uncaught ReferenceError: props is not defined 

this.props.blogs.map((blog, index) => {

には2つのコンポーネントです。

thisキーワードはusercsrf小道具に欠けている:あなたは `BlogFeed`をレンダリングする前に

<BlogCard {...blog} key={blog.blogIdHash} user={this.props.user} /> 
<Comments {...blog} key={index} blogId={blog.blogIdHash} csrf={this.props.csrf} /> 
関連する問題