2017-06-19 5 views
2

Reactでネストされたコメントを実装しようとしています。基本的に私は現在このコードを持っていますhereReactでネストされたコメントをレンダリングする

コードは次のようになります。

var nested = [...] 

function Comment({ comment }) { 
    const nestedComments = comment.map(comment => { 
    return <Comment comment={comment} />; 
    }); 

    console.log(nestedComments) 

    return (
    <div key={comment.id}> 
     <span>{comment.body}</span> 
     {nestedComments} 
    </div> 
); 
} 

ReactDOM.render(
    <Comment comment={nested}/>, 
    document.getElementById('container') 
); 

私は、次のようなエラーを取得しています:

Uncaught TypeError: comment.map is not a function 
at Comment (eval at transform.run (VM70 browser.js:5811), <anonymous>:947:31) 
at VM134 react-dom.js:4767 
at measureLifeCyclePerf (VM134 react-dom.js:4537) 
at ReactCompositeComponentWrapper._constructComponentWithoutOwner (VM134 react-dom.js:4766) 
at ReactCompositeComponentWrapper._constructComponent (VM134 react-dom.js:4741) 
at ReactCompositeComponentWrapper.mountComponent (VM134 react-dom.js:4649) 
at Object.mountComponent (VM134 react-dom.js:11551) 
at ReactDOMComponent.mountChildren (VM134 react-dom.js:10442) 
at ReactDOMComponent._createInitialChildren (VM134 react-dom.js:6176) 
at ReactDOMComponent.mountComponent (VM134 react-dom.js:5995) 

ない私がここで間違ってやっているものを確認してください。

答えて

1

私はあなたがコメント配列を二時間を渡すと、ネストされたコメントは存在しているかどうかを確認するか

をしようとする機能を変更する必要があります。この場合
var nested= [ 
    {comment_id: '..', 
    comment_body: '..', 
    comments: [{...}] 
    }, 
    ... 
] 

のようなあなたの構造があると信じて
var nested = [...] 

function Comment({ comment }) { 

    const nestedComments = null; 
    if(typeof comment === 'array') 
    nestedComments= comment.map(comment => { 
    return <Comment comment={comment.comments} />; 
    }); 

    console.log(nestedComments) 

    return (
    <div key={comment.id}> 
     <span>{comment.body}</span> 
     {nestedComments} 
    </div> 
); 
} 

ReactDOM.render(
    <Comment comment={nested}/>, 
    document.getElementById('container') 
); 
+0

彼のjsfiddleでコードを使用しているようです.. https://jsfiddle.net/9afdkb4b/ – WCMC

関連する問題