2017-06-19 159 views
2

我試圖在React中實現嵌套註釋。基本上我得到了這樣的代碼here在React中渲染嵌套註釋

的代碼如下所示:

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