I got an error:
Cannot read property 'map' of undefined
My JSON data:
{
"data": [
{
"id": 1,
"attention": 1
},
{
"id": 2,
"attention": 1
},
{
"id": 3,
"attention": 0
}
]
}
_handleOutput() {
var att = data.attention.map(function (data) {
return data.attention
});
}
console.log(att)
Is it possible to use if-else to compare the JSON output data to React DOM
? Something like this:
if (data.attention === true || "1") {
return <span>✅</span>;
} else {
return <span>❌</span>;
}
then i output into table list <td>{this._handleOutput()}</td>
let obj = {
data: [
{
id: 1,
attention: 1
},
{
id: 2,
attention: 2
},
{
id: 3,
attention: 0
}
]
}
inside component define render function
render(){
return (
<div>
{obj.data.map(a=>{
if(a.attention===1)
return <span>✅</span>
return <span>❌</span>;
})}
</div>
)
}
data
is array
, not data.attention
for this map
is not working. map
is working in the array.
You're trying to call map on a number field. It should be data.map
instead.
Data is your array not data.attention. So use like this:
{
"data": [
{
"id": 1,
"attention": 1
},
{
"id": 2,
"attention": 2
},
{
"id": 3,
"attention": 0
}
]
}
var att = data.map(function (data) {
return data.attention
});
console.log(att)
var data = [
{
"id": 1,
"attention": 1
},
{
"id": 2,
"attention": 2
},
{
"id": 3,
"attention": 0
}
]
var att = data.map(data => {
console.log(data);
if (data.attention === 1) {
return '<span>✅</span>';
} else {
return 'Not Fount';
}
});
console.log(att);
Mistake in the tried solution
Solution
Notes to improve
const jsonData = { "data": [{ "id": 1, "attention": 1 }, { "id": 2, "attention": 1 }, { "id": 3, "attention": 0 } ] } const App = () => { return ( <div> { jsonData.data.map(({attention}) => { return ( <div> { attention? <span>✅</span>: <span>❌</span> } </div> ) }) } </div> ) } ReactDOM.render(<App />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id='root'></div>
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.