Javascript 从.JSON访问值时出现问题(可能是路径问题)
我有一个使用api数据的react组件:Javascript 从.JSON访问值时出现问题(可能是路径问题),javascript,json,reactjs,Javascript,Json,Reactjs,我有一个使用api数据的react组件: class Item extends Component { constructor(props) { super(props); this.state = { output: {} } } componentDidMount() { fetch('http://localhost:3005/products/157963') .then(response => response.json())
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;
我需要从“images/primary”中的“large”访问image src链接。
在这里尝试了许多变体,但它总是以空或未定义对象的形式返回:/
const {images:{primary:{large}}} = this.state.output;
console.log(large)
您将在大变量中设置图像路径
您将拥有大变量中的图像路径。使用
this.state.output.images.primary.large
使用this.state.output.images.primary.large
谢谢!首先需要将其声明为空:const{images={primary:{large:“}}}}}=this.state.output,但它现在可以正常工作了。谢谢!首先需要将其声明为空:const{images={primary:{large:“}}}}}=this.state.output,但它现在可以正常工作了。
const {images:{primary:{large}}} = this.state.output;
console.log(large)