如何使用 ReactJS 从 promise 对象获取数据并将其放入 HTML 列表中?

How do I get data from a promise object and put it into an HTML list using ReactJS?

我正在使用承诺从 AWS SNS 获取主题列表,并将其记录到控制台。这很好用,但我遇到的问题是如何获取该信息并将其放入列表中,以便我可以在网页上显示它。

下面是将主题列出到控制台的代码:

    import AWS from 'aws-sdk';

    // Load the AWS SDK for Node.js
    AWS.config = new AWS.Config();
    AWS.config.accessKeyId = "My_Key";
    AWS.config.secretAccessKey = "My_Secret_Key";
    // Set region
    AWS.config.update({ region: 'My_Region' });
    // Create promise and SNS service object
    const ListTopicsPromise = new AWS.SNS({ apiVersion: '2010-03-31' 
    }).listTopics({}).promise();
    // Handle promise's fulfilled/rejected states

    ListTopicsPromise.then(
        function (data) {
           console.log(data.Topics);
        }).catch(
    function (err) {
        console.error(err, err.stack);
        });

我想我需要以某种方式将它变成一个函数,这样我就可以将它变成 return 一个 div 并在其中包含一个列表。我只是不确定该怎么做。您是否需要更多信息或有任何建议?感谢您抽出宝贵的时间来研究这个问题,而我一直在努力解决这个问题!

编辑:我从控制台日志中截取了一张图像,以防万一。

Console Topic List Snippet 这是来自 App.js:

的代码
import React, { Component } from 'react';
import './App.css';
import AWS from 'aws-sdk';
import awsmobile from './aws-exports';
import ListTopicsPromise from './aws/listTopics';

AWS.config.update({
    region: awsmobile.aws_cognito_region,
    credentials: new AWS.CognitoIdentityCredentials({
        IdentityPoolId: awsmobile.aws_cognito_identity_pool_id
    })
});

class App extends Component {
  state = {
    topics: [],
  }

  componentDidMount() {
    //Fetch data, then using 'setState' set it to topics.
    ListTopicsPromise.then(
      data =>
      this.setState({ topics: data.Topics})
    ).catch(
      err => {
        console.error(err, err.stack);
      });
  }
  render() {
    return (
      <div className="App">
        <div>
          {
            this.state.topics.map( topic =>
            <div>
              <p>Topic ID: {topic.id}</p>
              <p>Topic Title: {topic.title}</p>
            </div>
            )
          }
        </div>
      </div>
    );
  }
}

export default App;

该组件是使用 npx create-react-app my-app 安装 React 应用程序时出现的默认组件。

我们使用适当的生命周期方法来执行异步操作,就像您在此处所做的那样。获取数据后,我们将此数据设置为适当的状态 属性。这是我们使用 state 的地方。 componentDidMount 是一个合适的生命周期方法,所以:

 class App extends React.Component {
  state = {
    topics: [],
  }

  componentDidMount() {
    // Fetch data, then using `setState` set it to topics.
    ListTopicsPromise.then(
      data => 
        this.setState({ topics: data.Topics})
      ).catch(
        err => {
          console.error(err, err.stack);
        });
  }

  render() {
    return(
      <div>
      // map the data from state, then render it to the DOM.
      {
        this.state.topics.map( topic =>
          <div>
            <p>Topit Arn: {topic.TopicArn}</p>
          </div>
        )
      }
      </div>
    );
  }
}

注意: 您可以在另一个文件中设置 AWS thingy 并可以导出 ListTopicsPromise。我没有使用您代码中的这一部分。此外,我在 .then 回调中使用了箭头函数,因为我们在那里使用 this 上下文。