因此,我有一个显示来自数据的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以在我的应用程序中显示多个组件。不幸的是,我还无法弄清楚,因此在这里非常感谢您的帮助
答案 0 :(得分:2)
您可以从父组件中获取此urls数组作为道具,并映射到父组件中的数组。 示例:假设您有一个父组件App,其中包含此网址数组, 现在您必须在其上进行映射并调用您的子组件,即:每次迭代中的项。
//in your parent component
urls.map((url,index)=>{
return(
<Item key={index} url={url}/>
)
})
// now child component i.e: Item
//all code will be same just take the url from props instead of state while fetching
componentDidMount() {
fetch(this.props.url)
.then(response => response.json())
.then(data => this.setState({ output: data }));
}