Javascript 如何在其内部呈现React组件
我正在学习React,并尝试在其内部呈现Javascript 如何在其内部呈现React组件,javascript,reactjs,recursion,Javascript,Reactjs,Recursion,我正在学习React,并尝试在其内部呈现组件,但我遇到以下错误: TypeError: Cannot read property 'map' of undefined Comment._this.getResponses src/Comment.js:28 25 | ); 26 | } 27 | getResponses = () => { > 28 | return this.props.responses.map(p => { | ^ 29
组件,但我遇到以下错误:
TypeError: Cannot read property 'map' of undefined
Comment._this.getResponses
src/Comment.js:28
25 | );
26 | }
27 | getResponses = () => {
> 28 | return this.props.responses.map(p => {
| ^ 29 | return (
30 | <Comment
31 | author={p.author}
比如说:
return this.props.responses.map(p => {
return (
<div>
<h1>author={p.author}</h1>
<h1>avatar={p.avatar}</h1>
<h1>timeStamp={p.timeStamp}</h1>
<h1>text={p.text}</h1>
</div>
);
});
返回这个.props.responses.map(p=>{
返回(
作者={p.author}
阿凡达={p.avatar}
时间戳={p.timeStamp}
text={p.text}
);
});
代码工作。这是因为
的呈现依赖于定义的响应
当前,当您在getResponses()
中呈现Comment
组件时,没有响应
属性分配给这些注释:
<Comment
author={p.author}
avatar={p.avatar}
timeStamp={p.timeStamp}
text={p.text}
/>
return this.props.responses.map(p => {
return (
<div>
<h1>author={p.author}</h1>
<h1>avatar={p.avatar}</h1>
<h1>timeStamp={p.timeStamp}</h1>
<h1>text={p.text}</h1>
</div>
);
});
<Comment
author={p.author}
avatar={p.avatar}
timeStamp={p.timeStamp}
text={p.text}
/>
getResponses = () => {
// Check that responses prop is an array before
// attempting to render child Comment components
if(!Array.isArray(this.props.responses)) {
return null;
}
return this.props.responses.map(p => {
return (
<Comment
author={p.author}
avatar={p.avatar}
timeStamp={p.timeStamp}
text={p.text}
/>
);
});
};