Javascript 循环JS对象仅适用于return语句,否则将抛出undefined
第一个方法在JSX中包含return语句,可以正常工作Javascript 循环JS对象仅适用于return语句,否则将抛出undefined,javascript,reactjs,ecmascript-6,jsx,Javascript,Reactjs,Ecmascript 6,Jsx,第一个方法在JSX中包含return语句,可以正常工作 <div> {this.state.list.map(item => { return <h6>{item.location.formattedAddress[0]}</h6> })} </div> 但这通常会产生相同的结果: render() { const listItems = this.state.list.map((item, i
<div>
{this.state.list.map(item => {
return <h6>{item.location.formattedAddress[0]}</h6>
})}
</div>
但这通常会产生相同的结果:
render() {
const listItems = this.state.list.map((item, index) => (
<h6>{item.location.formattedAddress[0]}</h6>
));
return (
{listItems}
)
}
TypeError:无法读取未定义的属性“map”
此外,它在装载页面时运行,而不是在执行函数从API加载dat时运行,请有人协助
这是第一种与您相同的方法:
类应用程序扩展了React.Component{
构造器{
超级作物;
此.state={
名单:[
{id:1,标题:'React'},
{id:2,标题:'Angular'},
{id:3,标题:'Vue'}
]
};
}
渲染{
回来
{this.state.list&&this.state.list.mapli=>
{li.title}
}
;
}
}
ReactDOM.render,document.getElementById'root';
我建议您将listItems转换为renderListItems之类的方法,并在映射数组之前添加一个返回
renderListItems = () => {
return this.state.list.map((item, index) => (
<h6>{item.location.formattedAddress[0]}</h6>
));
}
然后在渲染方法中调用它,如
render() {
return (
<div>
{this.renderListItems()}
</div>
)
}
希望这对您有所帮助:理想情况下,它们的行为都是相同的,除非在render方法中,在执行{this.state.list.mapitem=>{return{item.location.formattedAddress[0]}}}而不是返回{listItems}之前返回某些内容。使用return listItems删除{}因为它返回一个具有属性listItems的对象。其次,在使用地图之前检查this.state.list,以防您的状态尚未填充。