[英]Get value from array inside fetch result (React.js)
I need to acess a name that is inside the array area_set that is inside a result from an API fetch. 我需要访问API提取结果内部的数组area_set中的名称 。 I try multiple ways but is says or that map is undefined
or something else. 我尝试了多种方式,但有人说或者map is undefined
或其他。
Here's the imagem of the json response: 这是json响应的图片:
Here's my code to ask for the 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);
});
})
}
Here's the code inside render method: 这是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>
);
}
}
I'm really stuck in this, anybody can help? 我真的陷入了困境,有人可以帮忙吗?
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>
);
}
}
Please try this way. 请尝试这种方式。 In your case state doesnot have area_set defined in it so there is a high chance of not finding some instant. 在您的情况下,状态中未定义area_set,因此很有可能找不到某个瞬间。 So it want you to handle that error 因此,它希望您处理该错误
{model.area_set.map(area =>
model.area.area_set[0].name
)}
This part looks weird. 这部分看起来很奇怪。 Try this instead: 尝试以下方法:
{model.area_set.map(area =>
area.name // This will yeild the name you are looking for once since the array is length = 1
)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.