簡體   English   中英

React:如何將數據作為道具從2個不同的API傳遞到單個組件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM