[英]React: How to pass data from 2 different API as props to a single component
我有一个页面(index.js),其中包含组件(slider.js)。 在index.js上,我使用了2个单独的API。 如果我将数据从第一个API发送到1个组件,并将数据从第二个API发送到另一个组件,则一切正常。
但是,我希望一个组件可以从第一个API接收一些值以及从第二个API接收一些值。
export default class extends React.Component {
static async getInitialProps() {
const apiUrl = 'https://api-1.com'
const res = await fetch(apiUrl)
const data = await res.json()
const apiUrl2 = 'http://api2.com'
const params2 = 'featured'
const res2 = await fetch(apiUrl2)
const data2 = await res2.json()
return { data, data2 }
}
componentDidMount() {
//logPageView()
}
render() {
return (
<div id='slider'>
{this.props.data.map(function (post, i) {
return (
<Slider
api1postSlug={post.slug}
//api2category={post2.slug}
/>
)
})}
</div>
}
如何将data2中的道具与{this.props.data.map(function (post, i) {
假设API 2具有相同的数据结构和API 1的行,则可以这样进行:
export default class extends React.Component {
static async getInitialProps() {
const apiUrl = 'https://api-1.com'
const res = await fetch(apiUrl)
const data = await res.json()
const apiUrl2 = 'http://api2.com'
const params2 = 'featured'
const res2 = await fetch(apiUrl2)
const data2 = await res2.json()
return { data, data2 }
}
componentDidMount() {
//logPageView()
}
render() {
return (
<div id='slider'>
{this.props.data.map(function (post, i) {
return (
<Slider
api1postSlug={post.slug}
api2category={this.props.data2[i].category}
/>
)
}, this)}
</div>
}
}
}
尝试添加if条件,然后返回如下。
render() {
if(this.props.data && this.props.data2) {
return (
<div id='slider'>
{this.props.data.map((post, i) => {
return (
<Slider
api1postSlug={post.slug}
api2category={this.props.data2[i].category}
/>
)
}, this)}
</div>
)
} else {
return (
<div id='slider'>Loading...</div>
)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.