[英]Cannot Access All Prop Data In Child Component
从父组件(主页)传递时,我无法访问完整的 API 调用作为子组件(属性)中的道具,子组件中的道具似乎还没有完全获取。
即props.housingData.address将在子组件中生成数据,但props.housingData.address不会。 错误信息:
错误:“无法访问未定义的行。”
```
export default class Home extends React.Component {
...
componentDidMount() {
var settings = {
"async": true,
"crossDomain": true,
"url":
"https://realtor.p.rapidapi.com/properties/v2/list-
for-rent?
sort=relevance&city=New%20York%20City&state_code=NY&limit=200&offset=0",
"method": "GET",
"headers": {
"x-rapidapi-host": "realtor.p.rapidapi.com",
"x-rapidapi-key": "API_KEY"
}
}
$.ajax(settings).done(response =>{
// Array to apply response iteration to
let dataArray = [];
//
// **I believe issue is here**
for(let i = 0; i < response.properties.length; i++){
let data = response.properties[i];
this.setState({housingData: data});
}
}
)
}
render() {
let dataLoaded = this.state.housingData;
return (
<div className="container">
<Grid container>
//Conditional to ensure fetch ---> {dataLoaded && this.state ?
<Property
housingData={this.state.housingData}
/>
: <CircularProgress className="loader" />}
</Grid>
</div>
)
}
}
```
export default function Property(props){
...
let propData = props.housingData
const propertyInfo = info.slice(0,showItems).map((info,item)=>(
<Card className={classes.root} }}>
<CardActionArea>
<CardMedia
component="img"
alt="Contemplative Reptile"
height="140"
// image={propData.photos[item].href}
image={info.img}
title="Contemplative Reptile"
/>
<CardContent>
<Typography gutterBottom variant="h5" component="h2">
{info.address}
</Typography>
</CardContent>
</Card>
))
我已经纠正了这个问题。 在将 API 响应发送到子组件之前,必须将 API 响应分配给父组件(主页)中的对象。 (属性)这是对子组件上的条件渲染集的补充,确保来自 api 的所有数据都已获取并分配给 props 以在子组件中使用。
export default class Home extends React.Component {
...
$.ajax(settings).done(response=>{
let dataArray = []; <--- // Set new empty array
for(let i = 0; i < response.properties.length; i++){
let obj = {}; <---- // Set Object
obj = {...response.properties[i]} <---- // Assigned response to object
dataArray.push(obj); <--- // Pushed to new array
}
this.setState({housingData: dataArray}); <--- // Send to state
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.