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 || {}
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?
There is no native .map
to {}
, so replace data.devices || {}
data.devices || {}
to 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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.