调用 Azure Cosmos DB 时如何在 React 中访问 PromiseResult api

How to get access to the PromiseResult in React when calling Azure Cosmos DB api

我正在尝试从 Cosmos DB 中提取一些行,然后通过它们进行映射以显示每个行的组件。我能找到的所有关于 Azure Cosmos DB API 的文档都将行一一记录到控制台,但我找不到然后告诉你如何 return 整个字符串。

我是新手,所以我可能做错了,但我现在被困住了,无法继续前进。希望你能帮助...

在我的 App.js 我有这个

function App() {
const [newMembers, setNewMembers] = useState(dataFetch());

在我的 dataFetch.js 我有

export default async function dataFetch() {
  const { endpoint, key, databaseId, containerId } = config;
  const client = new CosmosClient({ endpoint, key });
  const database = client.database(databaseId);
  const container = database.container(containerId);

  // Make sure Tasks database is already setup. If not, create it.
  // await dbContext.create(client, databaseId, containerId);

  try {
    console.log(`Querying container: Items`);

    // query to return all items
    const querySpec = {
      query: "SELECT * from c",
    };

    // read all items in the Items container
    const { resources: items } = await container.items
      .query(querySpec)
      .fetchAll();
    return items;
  } catch (err) {
    console.log(err.message);
  }
}

当我 console.log 结果返回时它说

Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Array(3)
0: {id: '154', forename: 'Fred', surname: 'Robson', address1: 'Some address', address2: 'Kingsmead', …}
1: {id: '416', forename: 'Lee', surname: 'Robson', address1: 'Some address', address2: 'Kingsmead', …}
2: {id: '900', forename: 'Kathryn', surname: 'Robson', address1: 'Some address', address2: 'Kingsmead', …}
length: 3
[[Prototype]]: Array(0)

我在其他地方看到了一些关于使用 .then 的东西,但是当我尝试时

const { resources: items } = await container.items
  .query(querySpec)
  .fetchAll()
  .then(() => {
    return items;
  });

它说“dataFetch.js:33 初始化前无法访问'items'”

您在前两个代码块中所做的完全没有问题。但是,通过将 dataFetch() 的结果置于 newMembers 状态,您只是将承诺存储在其中,该承诺在某个时候得到解决,您可以随时使用 [=13= 检索结果].

但是,我认为您更愿意将实际成员数组保持在 newMembers 状态。这可以通过例如:

function App() {
    const [newMembers, setNewMembers] = useState([]); // initially set to an empty array

    useEffect(() => {
        dataFetch().then(members => setMembers(members));
    }, []); // providing an empty array means: run this effect only once when this component is created.

    // do something with the newMembers. Initially, it will be [] 
    // but as soon as the data is retrieved from the DB, the actual data will be 
    // in the state and the component will be rerendered.
}