我'跟着一个带有reactJS的教程,我和#34; map"有一些问题。 TypeError:无法读取属性' map'未定义的
class GoalList extends Component{
componentDidMount(){
goalRef.on('value', snap=>{
let goals=[];
snap.forEach(goal =>{
const {email, title}=goal.val();
goals.push({email, title});
});
console.log('goals', goals);
this.props.setGoals(goals);
})
}
render(){
console.log('this.props.goals', this.props.goals);
return(
<div>
{this.props.goals.map((goal, index) => {
return (
<GoalItem key={index} goal={goal} />
)})}
</div>
)
}
答案 0 :(得分:1)
正如@developer在评论中所说,您的问题是您的代码引发了错误,因为当时未定义this.props.goals
而您无法map
超过undefined
}。
您可以通过提供默认值轻松解决此问题:
render(){
const { goals = [] } = this.props;
return(
<div>
{goals.map((goal, index) => {
return (
<GoalItem key={index} goal={goal} />
)})}
</div>
)
}
您也可以使用defaultProps
:
static defaultProps = {
goals: []
}