map is not a function in jsx

為{幸葍}努か 提交于 2019-12-24 19:18:58

问题


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. And also data.devices || {} to check if the devices property is there or not.

I console.log(data.devices) is return undefined but it should fallback to an object right? why is it still breaking?


回答1:


There is no native .map to {}, so replace data.devices || {} to data.devices || []

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



回答2:


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. 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.



来源:https://stackoverflow.com/questions/46481327/map-is-not-a-function-in-jsx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!