我需要在API提取结果内部的数组 area_set 中访问一个名称。我尝试了多种方法,但还是说map is undefined
或其他内容。
这是json响应的图片:
这是我要查询json的代码:
componentDidMount() {
fetch(url + '/couch-model/1/', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'JWT ' + (JSON.parse(localStorage.getItem('token')).token)
}
}).then(res => {
if (res.ok) {
return res.json();
} else {
throw Error(res.statusText);
}
}).then(json => {
this.setState({
model: json
}, () => {
console.log('model: ', json);
});
})
}
这是render方法中的代码:
render() {
const { model, isLoaded } = this.state;
if (!isLoaded) {
return (
<div id="LoadText">
Estamos a preparar o seu sofá!
</div>
)
} else {
return (
<div id="Esquerda">
<h2>
{model.area_set.map(area =>
model.area.area_set[0].name
)}
</h2>
<h1>{model.name}</h1>
<p>Highly durable full-grain leather which is soft and has a natural look and feel.</p>
<h3>Design</h3>
<h4>Hexagon</h4>
</div>
);
}
}
我真的陷入了困境,有人可以帮忙吗?
答案 0 :(得分:0)
getMeSomething = () => {
if(this.state.model.area_set)
return this.state.model.area_set.map(area => area.name)
}
render() {
const { model, isLoaded } = this.state;
if (!isLoaded) {
return (
<div id="LoadText">
Estamos a preparar o seu sofá!
</div>
)
} else {
return (
<div id="Esquerda">
<h2>
{this.getMeSomething()}
</h2>
<h1>{model.name}</h1>
<p>Highly durable full-grain leather which is soft and has a natural look and feel.</p>
<h3>Design</h3>
<h4>Hexagon</h4>
</div>
);
}
}
请尝试这种方式。在您的情况下,状态中未定义area_set,因此很有可能找不到某个瞬间。所以它希望您处理该错误
答案 1 :(得分:0)
{model.area_set.map(area =>
model.area.area_set[0].name
)}
这部分看起来很奇怪。尝试以下方法:
{model.area_set.map(area =>
area.name // This will yeild the name you are looking for once since the array is length = 1
)}