简体   繁体   English

等待 API 调用结果和更新列表组件

[英]Await result of API call and update list component

I am calling a REST API and return chat rooms.我正在调用 REST API 并返回聊天室。 Those get returned fine, as I can see in the payload of the object via the console.那些得到很好的返回,正如我可以通过控制台在对象的有效负载中看到的那样。

Now I want to display this in a list.现在我想在列表中显示它。

I was able to display a list and download the chat rooms, but not combine both.我能够显示列表并下载聊天室,但不能将两者结合起来。 This is what I did:这就是我所做的:

import * as React from 'react';

export default function ChatRoomList({param1}) {
  var x = getChatRoom(param1)
  console.log(x)

    return  (
        <div>
             <li>{param1}</li>
             <li> asd  </li>
             <li> asd  </li>
        </div>
    );
  }


async function getChatRoom(status) {

    // status could be either 'open' or 'room'
    var dict = { 
        chatType: status,
        };

    var adminChats = await callKumulosAPIFunction(dict, 'getAdminChat')
    return adminChats
}

Now I did try to simply await the first getChatRoom(param1) call.现在我确实尝试简单地await第一个getChatRoom(param1)调用。 But I can only await inside an async function.但我只能在异步函数中等待。 I then tried to add the async keyword to the export function, but this would crash the whole app.然后我尝试将 async 关键字添加到导出函数,但这会使整个应用程序崩溃。

How would the workflow be here?这里的工作流程如何? And how would I map the result from getChatRoom onto a listview?我如何将 getChatRoom 的结果映射到列表视图上?

The result of the adminChats (console.log(adminChats)): adminChats 的结果 (console.log(adminChats)):

在此处输入图片说明

You need to use useEffect hook to get remote data:您需要使用 useEffect 钩子来获取远程数据:

export default function ChatRoomList({param1}) {

  React.useEffect(()=>{
    (async () => {
        var x = await getChatRoom(param1)
        console.log(x)
    })()
  },[])  

    return  (
        <div>
             <li>{param1}</li>
             <li> asd  </li>
             <li> asd  </li>
        </div>
    );
  }

If the data returned from getChatRoom is an array and you want to show it, you need to save the response in a state, or the component will not re-render:如果 getChatRoom 返回的数据是一个数组,并且想要展示出来,则需要将响应保存在一个状态中,否则组件不会重新渲染:

export default function ChatRoomList({param1}) {
  const [chatRooms, setChatRooms] = React.useState([]);
  React.useEffect(()=>{
    (async () => {
        var x = await getChatRoom(param1)
        setChatRooms(x)
    })()
  },[])  

    return  (
        <div>
             <li>{param1}</li>
             {chatRooms.map((chatRoom , index) => {
                return <li key={index}>{JSON.stringify(chatRoom)}</li>
             })}
        </div>
    );
  }

async function getChatRoom(status) {

    // status could be either 'open' or 'room'
    var dict = { 
        chatType: status,
        };

    var adminChats = await callKumulosAPIFunction(dict, 'getAdminChat')
    return adminChats.payload
}

I suggest you to read the documentation about React hooks and lifecycle management:我建议您阅读有关 React hooks 和生命周期管理的文档:

  1. https://reactjs.org/docs/hooks-intro.html https://reactjs.org/docs/hooks-intro.html

  2. https://reactjs.org/docs/state-and-lifecycle.html https://reactjs.org/docs/state-and-lifecycle.html

You need to use useEffect hook to call the API.您需要使用useEffect hook 来调用 API。 Read more about hooks阅读更多关于钩子的信息

import * as React from 'react';

     function getChatRoom(status) {
        const [chats, setChats] = React.useState([]);
    
        const getChart = async (status) => {
            // status could be either 'open' or 'room'
            const  dict = { 
            chatType: status,
            };
    
            const adminChats = await callKumulosAPIFunction(dict, 'getAdminChat');
            setChats(adminChats);
        };
    
        React.useEffect(() => {
            getChart(status)
        }, [status])
    
    
        return { chats };
    };
    
    export default function ChatRoomList({param1}) {
      const { chats } = getChatRoom(param1)
      console.log(chats)
    
        return  (
            <div>
                 <li>{param1}</li>
                 {chats?.map((chatRoom , index) => {
                   return <li key={index}>{JSON.stringify(chatRoom)}</li>
                 })}
            </div>
        );
      }

Dependencies argument of useEffect is useEffect(callback, dependencies) useEffect Dependencies 参数是useEffect(callback, dependencies)

Let's explore side effects and runs:让我们探索副作用和运行:

Not provided: the side-effect runs after every rendering.未提供:副作用在每次渲染后运行。

import { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    // Runs after EVERY rendering
  });  
}

An empty array []: the side-effect runs once after the initial rendering.空数组 []:副作用在初始渲染后运行一次。

import { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    // Runs ONCE after initial rendering
  }, []);
}

Has props or state values [prop1, prop2, ..., state1, state2] : the side-effect runs only when any dependency value changes.有道具或状态值[prop1, prop2, ..., state1, state2] :副作用仅在任何依赖值更改时运行。

import { useEffect, useState } from 'react';

function MyComponent({ prop }) {
  const [state, setState] = useState('');
  useEffect(() => {
    // Runs ONCE after initial rendering
    // and after every rendering ONLY IF `prop` or `state` changes
  }, [prop, state]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM