我正在構建一個反應應用程式,我正在設定stateofapi但是狀態并沒有按照我想要的方式設定nested response。nested state
收到的回應api
[
{
"id": 70,
"title": "feefifef",
"images": [
{
"id": 28,
"text": "First Image"
"blog_id": 70,
},
{
"id": 28,
"text": "First Image",
"blog_id": 70,
}
]
}
]
應用程式.js
class App extends React.Component {
constructor(props){
super(props)
this.state = {
blogs = [
{
id: 0,
title: "",
images: [
{
id:0,
text:""
}
]
}
]
}
}
componentDidMount() {
let data;
axios.get('http://127.0.0.1:8000/api/blogs/').then((res) => {
data = res.data;
this.setState({
blogs: data.map((blog) => {
return Object.assign({}, blog, {
id: blog.id,
title: blog.title,
images: blog.images,
}
})
})
})
}
render() {
const blogs = this.state.blogs.map((blog) => (
<BlogList
id={blog.id}
title={blog.title}
images={blog.images}
/>
))
}
return (
<div>{blogs}</div>
)
}
class BlogList extends React.Component {
constructor(props){
super(props)
}
return (
<div>
Title: {this.props.title}
Images: {this.props.images}
</div>
)
}
問題是什么 ?
之后不顯示影像Title。我正在嘗試在BlogList每個博客的類中顯示所有影像。
我也嘗試過使用 (in BlogList class)
this.props.images.map((img) => {
return (
<div>
Title: {this.props.title}
Images: {img.text}
</div>
)
}
但它向我展示了
this.props.images.map 不是函式。
然后我認為問題出setting state在影像上(我可能錯了)。
當我嘗試列印this.props.images時,它顯示
0: {id: 28, text: '1111', blog_id: 71}
length: 1
[[Prototype]]: Array(0)
我是新的反應,任何幫助將不勝感激。先感謝您
uj5u.com熱心網友回復:
this.props.images 是一個陣列,因此您不能直接使用 {this.props.images}。否則,您將收到類似這樣的錯誤“物件作為 React 子項無效。如果您要渲染子項的集合,請改用陣列”
你必須使用這樣的東西
render() {
return (
<div>
Title: {this.props.title} <br/>
Images:
{this.props.images?.map((image, i) => (
<div key={image.id}>
{image.id}<br/>
{image.text}<br/>
{image.blog_id} <br/>
</div>
))}
</div>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/480278.html
標籤:javascript 反应 字典
