因此,我有一个类组件,可从API加载一些数据:
class Item extends Component {
constructor(props) {
super(props);
this.state = {
output: {}
}
}
componentDidMount() {
fetch(item_url[0])
.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>
);
}
}
export default Item;
它可以与API一起正常使用,从此数组中插入了地址(URL):
let item_url = [
'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'];
我想在这里实现的功能是多次渲染此组件(每次使用另一个API数据)。我想这里需要某种循环功能,但无法弄清楚。现在,它是从我的index.js呈现的,如下所示:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Item from './DataHarvester'
ReactDOM.render([<Item />, <App />], document.getElementById('root'));
但是显然,当我需要10个组件时,它仅创建一个组件。
答案 0 :(得分:0)
您可以使用map
来执行此操作;通常,模式如下:
map
状态产生子组件
const Section = (props) => (
<p>{props.url}</p>
);
const App = () => {
const 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'
];
return (
<div>
{urls.map(x => <Section url={x}/>)}
</div>
);
};
ReactDOM.render(<App />, document.getElementById('r'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="r"></div>