我正在研究一个小项目,我打算在一个组件中呈现所有API内容并分步显示,例如:
第1页:选择引擎
第2页:选择颜色
第3页:选择轮子
但是我无法映射此API的数组。
应用程序组件:
constructor() {
super();
this.state = {
correntEngine: null,
correntColor: null,
correntWheel: null,
engine: [],
color: [],
wheels: [],
finalPrice: null,
}
}
componentDidMount() {
this.fetchBuildCar();
}
fetchBuildCar = async () => {
const response = await api.get();
const buildCar = response.data.data;
this.setState({
engine: buildCar.engine,
color: buildCar.color,
wheels: buildCar.wheels
})
}
render() {
const buildCar = this.state;
return (
<Router>
<Container>
<div className="row content-home">
<Col lg={6}>Image</Col>
<Col lg={6}>
{buildCar.engine.items.map(item => (
<h1>{item.type}</h1>
))}
</Col>
</div>
</Container>
</Router>
)
}
}
export default ContentApp;
API:
{
"data": {
"price": 63000,
"engine": {
"items": [
{
"type": "P",
"kwh": 75,
"range": 275,
"price": 0,
"id": 1
},
{
"type": "S",
"kwh": 100,
"range": 355,
"price": 5500,
"id": 2
},
{
"type": "B",
"kwh": 125,
"range": 420,
"price": 10000,
"id": 3
}
]
},
"color": {
"description": "The 2009 Model R have 3 unique metalic color options. Each color was meticulously developed to look like something completely new to your eyes.",
"items": [
{
"hexadecimal": "#AB1725",
"label": "Metalic Vermilion",
"price": 0,
"id": 4
},
{
"hexadecimal": "#0F1C2D",
"label": "Thunderbolt Blue",
"price": 1200,
"id": 5
},
{
"hexadecimal": "#A8A8A8",
"label": "Space Grey",
"price": 1200,
"id": 6
}
]
},
"wheels": {
"items": [
{
"label": "20” Silver Metalic",
"price": 0,
"id": 7
},
{
"label": "20” Grafitti",
"price": 2000,
"id": 8
},
{
"label": "22” Performance Carbon",
"price": 2000,
"id": 9
}
]
}
}
}
当我映射“项目”时,返回无法读取未定义的属性“ map”。我该怎么解决?
答案 0 :(得分:0)
buildCar
在呈现范围中不存在,您必须改为使用状态。
{this.state.engine.items.map(item => (
<h1>{item.type}</h1>
))}
答案 1 :(得分:0)
我已经尝试过您的代码,并且效果很好。检查下面的图片。
实际上,您的问题与map
无关。
主要问题是render()函数在fetchApi返回之前运行。
所以写这样的代码。
{buildCar.engine && buildCar.engine.items && buildCar.engine.items.map(item => ...
答案 2 :(得分:0)
您需要检查在使用componentDidMount
时是否确实存在数据,因为组件首先以您的默认状态呈现。您应该这样做,
{buildCar.engine.items && buildCar.engine.items.map(item => (
<h1 key={item.id}>{item.type}</h1>
))}