next.js 错误:无法解构“(中间值)”的属性“devices”,因为它未定义

oipij1gg  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(127)

我在一个page.txs文件中有以下函数来获取JSON响应并在Next 13应用程序的页面中使用它

const getDevices = async () => {
      try {
          const res = await fetch('/api/getdevice',{ cache: 'no-store' })
          if (!res.ok){
            throw new Error("Failed to get device list")
          }
          return res.json();
      } catch (error){
          console.log("Error loading devices: ", error);
      }
    }

在同一个文件中,我有我的主页面函数,它通过一个javascript调用getDevices,但我一直得到错误错误:无法解构“(中间值)”的属性“devices”,因为它未定义。

const HomePage = async () => {

   const {devices} = await getDevices();
   

  return (
    <>
 

    {devices.map((device)=> ...

错误消息

TypeError: Cannot destructure property 'devices' of '(intermediate value)' as it is undefined.
    at HomePage (./app/home/page.tsx:46:13)
digest: "3194401674"
> 50 |    const {devices} = await getDevices();
     |          ^
tez616oj

tez616oj1#

感谢您的useEffect建议。为了解决这个问题,我将其 Package 在一个use Effect函数中

const HomePage = () => {
  const [devices, setDevices] = useState();
 useEffect(() => {
    /* Load Devices */
    async function fetchDeviceData() {
      let deviceList = await getDevices();
      if (deviceList) {

相关问题