class Home extends Component{ componentDidMount(){ this.props.getCustomer() } render(){ const {total, list} = this.props.customer console.log("total:"+total) console.log("list:"+list) return( <div> <NavBar>客戶管理系統</NavBar> {list.map((item,index)=>( <List key={index}> <Item arrow="horizontal" thumb="https://zos.alipayobjects.com/rmsportal/dNuvNrtqUztHCwM.png" multipleLine onClick={() => {}} > 客戶名稱:{item.name} <Brief>級別:{item.level}</Brief> </Item> </List> ) ) }
</div>
)
報錯:Cannot read property 'map' of undefine
原因:調用map的對象是 undefined,初始化第一次渲染的時候異步數據返回之前list是undefined。
解決方法:對list作判斷,異步ajax返回數據list取到值后再渲染組件。
修改如下:
{list && list.map((item,index)=>( <List key={index}> <Item arrow="horizontal" thumb="https://zos.alipayobjects.com/rmsportal/dNuvNrtqUztHCwM.png" multipleLine onClick={() => {}} > 客戶名稱:{item.name} <Brief>級別:{item.level}</Brief> </Item> </List> ) ) }