简体   繁体   English

map不是jsx中的函数

[英]map is not a function in jsx

This block of code caused error of map is not a function 此代码块导致映射错误不是功能

 {data && (data.devices || {}).map((obj, i) => 
    <div>{obj.name}</div>
 )}

I just don't get it, I already did data && to check data is defined else keep the map. 我只是不明白,我已经做了data &&检查数据是否已定义,否则保留地图。 And also data.devices || {} 还有data.devices || {} data.devices || {} to check if the devices property is there or not. data.devices || {}检查devices属性是否存在。

I console.log(data.devices) is return undefined but it should fallback to an object right? console.log(data.devices)返回未定义,但它应该回console.log(data.devices)对象吗? why is it still breaking? 为什么它仍在中断?

There is no native .map to {} , so replace data.devices || {} {}没有本机.map ,因此请替换data.devices || {} data.devices || {} to data.devices || [] data.devices || {}data.devices || [] data.devices || []

{(data && data.devices || []).map((obj, i) => 
    <div>{obj.name}</div>
)}

In this case map is not a function because when data.devices is empty, the default value is an empty object hence map is not a function of an object. 在这种情况下, map不是函数,因为当data.devices为空时,默认值为空对象,因此map不是对象的函数。 Take this for example: 以这个为例:

 // simulate scenarios const data00 = undefined; const data01 = {}; const data02 = { devices: null }; const data03 = { devices: [] }; const data04 = { devices: [{ name: 'device01' }, { name: 'device02' }] } class Main extends React.Component { render() { return ( <div> {this.load(data00)} {this.load(data01)} {this.load(data02)} {this.load(data03)} {this.load(data04)} </div> ); } /** * Loads data and renders the devices if there's any */ load(data) { return (!!data && data.devices || []).map((obj, i) => <div key={i}>{obj.name}</div> ); } } ReactDOM.render(<Main />, document.getElementById('main')); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="main"/> 

As you can see, only data04 's devices will be rendered. 如您所见,将仅呈现data04的设备。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM