我试图在React中实现嵌套注释。基本上我得到的代码目前就像这个here。
代码如下所示:
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)
不确定我在这里做错了什么。
答案 0 :(得分:1)
我相信你的结构就像
var nested= [
{comment_id: '..',
comment_body: '..',
comments: [{...}]
},
...
]
在这种情况下,您应该更改函数以第二次传递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')
);