Hello I am trying to loop through a list object and render an object with each entry of the list. However, I kept running into the same error.. I am also wondering how can I see if I a setting the state correctly?
Here is the error that I get
Uncaught TypeError: Cannot read property 'map' of undefined
at Feed.render (bundle.js:11417)
at finishClassComponent (bundle.js:7881)
at updateClassComponent (bundle.js:7878)
at beginWork (bundle.js:7974)
at performUnitOfWork (bundle.js:8294)
at workLoop (bundle.js:8318)
at HTMLUnknownElement.callCallback (bundle.js:6296)
at Object.invokeGuardedCallbackDev (bundle.js:6312)
at invokeGuardedCallback (bundle.js:6251)
at performWork (bundle.js:8354)
Here is my json on API:
{
"next": "",
"posts": [
{
"postid": 3,
"url": "/api/v1/p/3/"
},
{
"postid": 2,
"url": "/api/v1/p/2/"
},
{
"postid": 1,
"url": "/api/v1/p/1/"
}
],
"url": "/api/v1/p/"
}
Here is my obj class:
constructor(props) {
// Initialize mutable state
super(props);
this.state = { posts: []};
}
componentDidMount() {
// Call REST API to get number of likes
fetch(this.props.url, { credentials: 'same-origin' })
.then((response) => {
if (!response.ok) throw Error(response.statusText);
return response.json();
})
.then((data) => {
this.setState({
posts: data.posts,
});
})
.catch(error => console.log(error));
}
render() {
const nums = [1,2,3,4,5,6]
var newData = Array.from(this.state.posts)
return (
<ul>
{this.state.newData.map((post)=> (
<li>post</li>
))}
</ul>
);
}
}
You do not have newData
stored in your component's state object.
newData
is scoped locally to the render()
method.
This should be solved by simply replacing this.state.newData.map(...)
with newData.map(...)
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.