I have a react component that uses api data:
class Item extends Component {
constructor(props) {
super(props);
this.state = {
output: {}
}
}
componentDidMount() {
fetch('http://localhost:3005/products/157963')
.then(response => response.json())
.then(data => this.setState({ output: data }));
}
render() {
console.log(this.state.output);
const { general = {name:""} } = this.state.output;
const { id } = this.state.output;
const { images = {large:""} } = this.state.output;
return (
<ItemPanel>
<ItemBox>
<BoxTitle>{general.name}</BoxTitle>
<BoxId>Item ID: {id}</BoxId>
<Details onClick={show_details}>Show more...</Details>
<Inline>
<Quantity type="number" defaultValue="1"></Quantity>
<Icon>add_shopping_cart</Icon>
</Inline>
<AddItem>
<Sfont>Add to cart</Sfont>
</AddItem>
</ItemBox>
<BoxImg src={images} alt='img error'></BoxImg>
</ItemPanel>
);
}
}
export default Item;
and this is what .JSON look like:
{
"id": "774944",
"general": {
"presentable_id": "774944",
"name": "Blekk BROTHER LC1280XLC blå",
"description": ""
},
"brand": {
"name": "Brother Norge AS"
},
"images": {
"primary": {
"large": "https://i.imgur.com/zYcibjw.jpg"
}
}
}
I need to access the image src link from "large" in 'images/primary'. Have tried many variations here, but it always returns as empty or undefined object :/
const {images:{primary:{large}}} = this.state.output;
console.log(large)
you'll have the image path in large variable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.