簡體   English   中英

從.JSON訪問值的問題(可能是路徑問題)

[英]Problem with accessing value from .JSON (path issue probably)

我有一個使用api數據的react組件:

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;

這就是.JSON的樣子:

{
"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"
  }
}
}

我需要從“ images / primary”中的“ large”訪問image src鏈接。 在這里嘗試了許多變體,但它總是返回為空或未定義的對象:/

const {images:{primary:{large}}} = this.state.output;
console.log(large)

您將在大變量中使用圖像路徑。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM