I am using a JSON placeholder object to place the object name in each list item. I keep getting "undefined" instead of the data.name.
Thanks for reading! Here is my code below for you to look at:
console.clear()
class App extends React.Component {
searchFunction() {
fetch('http://jsonplaceholder.typicode.com/posts/1/comments', {
method: 'GET'
}).then((res) => {
res.json().then((data) => {
console.log(data);
data.forEach(function()
{document.getElementById('datalog').innerHTML+=
`<ul>
<li>
${data.name}
</li>
</ul>`
});
})
})
.catch((err) => {
console.log(err);
})
}
render() {
return (
<div className='App'>
<h1>Welcome to VCP!</h1>
<div id="datalog"></div>
{this.searchFunction()}
</div>
)
}
}
ReactDOM.render(
<App/>,
document.getElementById('root')
)
you forgot to pass in an argument to your forEach
call, if should be like this:
console.clear()
class App extends React.Component {
searchFunction() {
fetch('http://jsonplaceholder.typicode.com/posts/1/comments', {
method: 'GET'
}).then((res) => {
res.json().then((data) => {
console.log(data);
data.forEach(function(item){document.getElementById('datalog').innerHTML+=
`<ul>
<li>
${item.name}
</li>
</ul>`
});
})
})
.catch((err) => {
console.log(err);
})
}
render() {
return (
<div className='App'>
<h1>Welcome to VCP!</h1>
<div id="datalog"></div>
{this.searchFunction()}
</div>
)
}
}
ReactDOM.render(
<App/>,
document.getElementById('root')
)
您不能在js函数中使用$ {data.name}。它应该类似于document.getElementById('datalog')。innerHTML + = <ul> <li>'+data.name+' </li> </ul>
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.