javascript - 获取数据之前的渲染组件已经完成

标签 javascript react-native fetch state

我正在尝试通过创建函数来获取数据。在该函数中,我正在尝试设置状态,并且从 componentDidMount 调用它。方法,但我遇到了一些问题:

  1. 我不确定是否 while这是一个很好的实践,因为我正在循环并更改我的端点,这样我每次都可以获得新数据。
  2. 我尝试从获取函数返回数据并使用 setState里面componentDidMount ,但我遇到了问题,我怀疑是因为 componentDidMount在获取完成之前正在运行
  3. 我尝试过使用 res.json()使用 promise 对数据进行处理,但我收到错误 res.json不是一个函数。
state = {
    title: [],
    image: [],
    rating: [],
  };

getData =  () => {
    let i = 1;
    while (i <= 9) {
       axios.get(`http://api.tvmaze.com/shows/${i}`)
      .then(response => console.log(response))
      .then(response => this.setState({
        title:response.data.data.name[i],
      }))
      .catch(error => console.log(error));
      i++;
    }
  };
  componentDidMount() {
    this.getData();
    console.log(this.state.title);
  }

最佳答案

如果您的目标是在获取信息后渲染您的 JSX,那么我建议您在 state 中创建一个附加项目,isLoading ,您可以将其设置为 truefalse 并有条件地渲染您的 JSX

根据您在下面提供的示例,它看起来如下所示:

class Shows extends React.Component {
  state = { 
    title: [], 
    image: [],
    rating: [],
    isLoading: true
  }

  componentDidMount() {
    this.getData()
  }

  getData = () => {
    // I've created a URL for each request
    const requestUrls = Array.from({ length: 9 })
      .map((_, idx) => `http://api.tvmaze.com/shows/${idx + 1}`);

    const handleResponse = (data) => {
      // `data` is an array of all shows that you've requested

      // extract information about each show from the payload
      const shows = data.map(show => show.data)

      // handle shows data however you need it
      // and don't forget to set `isLoading` state to `false`
      this.setState({
        isLoading: false,
        title: shows.map(show => show.name),
        image: shows.map(show => show.url),
        rating: shows.map(show => show.rating.average),
      })
    }
    const handleError = (error) => {
      // handle errors appropriately
      // and don't forget to set `isLoading` to `false`
      this.setState({
        isLoading: false
      })
    }

    // use `Promise.all()` to trigger all API requests
    // and resolve when all requests are completed
    Promise.all(
      requestUrls.map(url => axios.get(url))
    )
      .then(handleResponse)
      .catch(handleError)
  }

  render() {
    const { isLoading, title, image, rating } = this.state

    // prevent showing your `JSX` unless data has been fetched
    // ideally, show a loading spinner or something that will
    // tell users that things are happening; 
    // returning `null` won't render anything at all
    if (isLoading) {
      return null
    }
    return (
      <div>...</div>
    )
  }
}

这样,使用 Promise.all,就可以更轻松地推理您正在进行的所有这些调用。

除此之外,使用 componentDidMount 从 API 获取数据是正确的位置,但我会远离 while 循环并使用 Promise.all 用于所有请求,并 map 创建一组可传递给 Promise.all 并在以下位置处理的 promise (请求)一次。

工作示例:

关于javascript - 获取数据之前的渲染组件已经完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57540211/

相关文章:

reactjs - 如何在 NextJS 中为 getStaticProps 导入 API 路由?

Javascript 表单提交两次

javascript - 如何删除 div 的可拖动事件?

javascript - 如何自定义daterangepicker(ngxDaterangepickerMd)

javascript - 如何仅针对导航器屏幕之一禁用抽屉导航滑动?

ios - 当应用程序在后台时使用 React Native 静默 iOS 推送通知

react-native - 派送后如何更新状态

php - 拉维尔 5.1 : how to fetch on separate table

javascript - Angular Firestore 根据返回的 bool 值显示一个按钮,该 bool 值检查 Firestore 文档是否存在

javascript - 如何根据特定选项更改文本颜色?