![](/img/trans.png)
[英]object.js with state in react ( Cannot read property 'map' of undefined)
[英]Fail to set state REACT/JS: Cannot read property 'map' of undefined
您好,我正在嘗試遍歷列表 object 並使用列表的每個條目呈現 object。 但是,我一直遇到同樣的錯誤。我還想知道如何查看我是否正確設置了 state?
這是我得到的錯誤
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)
這是我在 API 上的 json:
{
"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/"
}
這是我的 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>
);
}
}
您的組件的newData
object 中沒有存儲 newData。
newData
在本地限定為render()
方法。
這應該通過簡單地將this.state.newData.map(...)
替換為 newData.map(... newData.map(...)
來解決
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.