【问题标题】:How to fetch and display data from two different APIs如何从两个不同的 API 获取和显示数据
【发布时间】:2021-07-26 21:43:02
【问题描述】:

因此,我正在学习 React,并被困在从两个不同的 API 获取数据并将数据显示到同一个表中。我可以显示来自第一个 API 的数据,我从中获取编号和名称,但是当我尝试显示来自第二个 API 的数据以获取流派时,它不再起作用了。我什至不确定我是否可以这样做,但希望有人可以提供帮助。

class Stops extends React.Component {
  constructor () {
    super()
    this.state = {
      books: [],
      authors: []
    }
  }
  componentDidMount () {
    fetch('/url1')
      .then((res) => {
        res.json()
          .then(data => this.setState({ books: data }))
      })
    fetch('/url2')
      .then((response) => {
        response.json()
          .then(authorData => this.setState({authors: authorData }))
      })
  }
  Displayauthors (authors) {
    return authors.map((author) => (
      <div key={author.authorId}>
         {author.genre}
      </div>
    ))
  }
  render () {
    const books = this.state.books
    return (
      <div>
        <table>
          <thead>
            <tr>
              <th>number</th>
              <th>name</th>
              <th>Genre</th>
              <th>Download book</th>
            </tr>
          </thead>
          <tbody>
            {
             books.map((book) => (
                <tr key={book.id}>
                  <td>{book.number}</td>
                  <td>{book.name}</td>
                  <td>{this.displayAuthors(this.state.authors)}</td>
                  <td><button type="button">Download</button></td>
               </tr>
             ))
            }
          </tbody>
        </table>
      </div>
    )
  }
}

【问题讨论】:

    标签: reactjs frontend backend display fetch-api


    【解决方案1】:

    您可以尝试获取数据,但不能直接进入状态。 而是在状态中创建类似“allStuffLoadedNow”标志的东西。

    工作流程

    如果fetch 1成功,它将结果数据写入一个局部变量(可能是this.prop.fetchResult1Fetch 2this.prop.fetchResult2 做同样的事情。

    在每个success(两个提取请求)之后,检查other 提取的fetchResult 是否仍然完成(例如,检查this.prop.fetchResult1!==null 是否仍然完成)。 如果不是null,则将状态变量allStuffLoadedNow 设置为true,这会导致页面重新呈现。

    现在您可以使用两个 fetchResults。

    希望这能给你一个想法,如何解决。

    【讨论】:

      【解决方案2】:

      你应该把值放在你的div中

      <div key={author.authorId} value={genre}>
              {author.genre}
           </div> 
      

      你的也一样

      <tr key={book.id} value={(number, name)}>
      

      对于 API 请求,您可以使用 axios

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-15
        • 1970-01-01
        • 1970-01-01
        • 2020-04-03
        相关资源
        最近更新 更多