【发布时间】:2019-06-11 07:51:16
【问题描述】:
所以,我有一个从数据中显示 API 的类组件。链接作为道具从数组中插入,一切正常:
let urls = [
'http://localhost:3005/products/774944',
'http://localhost:3005/products/774945',
'http://localhost:3005/products/774946',
'http://localhost:3005/products/123581',
'http://localhost:3005/products/782691',
'http://localhost:3005/products/782485',
'http://localhost:3005/products/782486',
'http://localhost:3005/products/782487',
'http://localhost:3005/products/782488',
'http://localhost:3005/products/738471'];
class Item extends Component {
constructor(props) {
super(props);
this.state = {
output: {},
url: ulrs[0]
}
}
componentDidMount() {
fetch(this.state.url)
.then(response => response.json())
.then(data => this.setState({ output: data }));
}
render() {
console.log(this.state.output);
const { general = {name:"", description:""} } = this.state.output;
const { brand = {name : ""} } = this.state.output;
const { id } = this.state.output;
const {images = {primary:{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.primary.large} alt='img error'></BoxImg>
</ItemPanel>,
<DetailsView id="details_view">
<ItemDetails id='details_id'>
<Close onClick={show_details}>x</Close>
<BoxTitle>{general.name}</BoxTitle>
<BigImg src={images.primary.large} alt='img error'></BigImg>
<BoxId>Item ID: {id}</BoxId>
<Brand>Made by: {brand.name}</Brand>
{Parser(general.description)}
<Inline>
<Quantity type="number" defaultValue="1"></Quantity>
<Icon>add_shopping_cart</Icon>
</Inline>
<AddItem>
<Sfont>Add to cart</Sfont>
</AddItem>
</ItemDetails>
</DetailsView>
]);}}
我想做的是某种功能,它基于一个模板创建多个组件,但使用来自 API 的不同数据。我正在尝试这样的事情:
let Show_items = React.createClass({
render: function() {
let urls = [
'http://localhost:3005/products/774944',
'http://localhost:3005/products/774945',
'http://localhost:3005/products/774946',
'http://localhost:3005/products/123581',
'http://localhost:3005/products/782691',
'http://localhost:3005/products/782485',
'http://localhost:3005/products/782486',
'http://localhost:3005/products/782487',
'http://localhost:3005/products/782488',
'http://localhost:3005/products/738471'];
let ItemsReady = urls.map(function(link, index){
return {Item(link)};
})
return ItemsReady;
}});
我的目标是将 ItemsReady 导出到 index.js 并将其渲染到 DOM 以在我的应用程序中显示多个组件。不幸的是我还没有弄明白,所以在这里非常感谢帮助
【问题讨论】:
标签: javascript reactjs