等到Promise解决后,再将其结果传递给React返回语句

时间:2018-12-19 22:05:29

标签: javascript reactjs promise async-await

我这里有这个对象组件,是从本地服务器上从中获取数据的,我需要等到数据下载后,再将信息传递给组件的return语句。我尝试了很多事情,但似乎没有用。这是我的最后尝试:

import React, { Component } from 'react';
import ReviewItem from './review_item.js'

const ReviewList = async (props) => {

  const form = {
       elementPlayground:"2019A.Kagan",
       elementId:props.element_id,
       type:"ShowReviews",
       attributes: { page:0, size:5 }
  }

  const url = `http://localhost:8083/playground/activities/2019A.Kagan/${props.playground}`

  const getItems = () => {
    return fetch(url, {
                method: "POST",
                mode: "cors",
                headers: {
                  "Content-Type": "application/json",
                },
                body: JSON.stringify(form),
              })
              .then(response => response.json())
              .then(json => ((json['attributes'])['reviews']).map(review => <ReviewItem key={json['id']} review={review} />));
  }

    const items = await getItems();
    console.log(items);
    return (
      <ul className="col-md-4 list-group">
      {items}
      </ul>
    )
}

export default ReviewList;

我要退回的商品是“商品” 我将不胜感激!

1 个答案:

答案 0 :(得分:0)

这通常仍然是新事物,但是如果我等待显示数据的响应或阻止进一步的子项加载,我通常将state设置为isLoading: true,然后在提取成功完成时设置isLoading: false

如果有帮助,可以这样。

return (
  <ul className="col-md-4 list-group">
  {!this.state.isLoading && {items}}
  </ul>
)