[英]React API object in JavaScript keeps saying undefined
I am using a JSON placeholder object to place the object name in each list item. 我正在使用JSON占位符对象将对象名称放置在每个列表项中。 I keep getting "undefined" instead of the data.name.
我一直在获取“未定义”而不是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: 您忘记将参数传递给
forEach
调用,如果是这样的话:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.