【发布时间】:2020-12-31 18:53:56
【问题描述】:
我无法从父组件访问完整的 API 调用作为子组件中的道具。通过 props 将 fetch 传递给子组件。
即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 获取数据之前不要渲染子组件,或者对响应中的每个键使用适当的检查。顺便说一句,您的问题标题误导了正文
-
感谢您的反馈。稍后将尝试再次使用它。另外,我正在寻找一种编辑标题的方法。第一次在这里发海报。再次感谢。
标签: javascript arrays reactjs api react-props