使用 React 进行数据 Fatch (Nextjs)

问题描述 投票:0回答:1

我正在使用 next.js,并且正在从 json 中获取数据。现在我看不到 json 中的数据(刷新时会发生变化),例如在表格的第一个框中。

有人可以帮助我吗?我试了这么多天还是没解决。

import styles from "../styles2/Tabelle.module.css" 
import {useEffect, useState} from "react";

export default  function  Fetch() {
    "use client"
      const [appState, setAppState] = useState([]);
    useEffect(() => {
        const fetchData = async () => {
        const response = await fetch("https://run.mocky.io/v3/f3bf41f3-c60a-47f8-9386-243989bead65");
        const json = await response.json();
        setAppState(json);
        };
        fetchData();
    }, []);

    const date = ( <ul>
        {appState.map((item) => 
           <li key= {item.id}> {item.id} </li>
       )}  
       </ul>
       );
return(

< div > 
<table>
    <thead> 
    <tr>
        <th>ID ESECUZIONE </th> <th>NOME PROCESSO</th> <th>HOST</th> <th>ANDAMENTO</th> <th>DURATA</th> <th>AVANZAMENTO</th> </tr>
    </thead>
    <tbody >
    <tr className={styles.righeEsecuzioni}>
    <td> {date.key} </td>  </tr>
    </tbody>

</table>
    </div>

)}
reactjs next.js fetch-api nsfetchrequest urlfetch
1个回答
0
投票

响应字符串的开始和结束不包含数组括号[]

使用axios库,你可以这样做

导入库

 import axios from 'axios';

获取数据

 const response = await axios.get(
    'https://run.mocky.io/v3/f3bf41f3-c60a-47f8-9386-243989bead65'
  );

现在在开始和结束处添加括号

 const string = '[' + response.data + ']';

现在设置状态

setAppState(JSON.parse(string));

整体代码如下

 import { useEffect, useState } from 'react';
import axios from 'axios';

export default function Fetch() {
  'use client';
  const [appState, setAppState] = useState([]);
  useEffect(() => {
    const fetchData = async () => {
      const response = await axios.get(
        'https://run.mocky.io/v3/f3bf41f3-c60a-47f8-9386-243989bead65'
      );
      const string = '[' + response.data + ']';
      setAppState(JSON.parse(string));
    };
    fetchData();
  }, []);
  const date = (
    <ul>
      {appState.map((item: any) => (
        <li key={item.id}> {item.id} </li>
      ))}
    </ul>
  );
  return (
    <div>
      <table>
        <thead>
          <tr>
            <th>ID ESECUZIONE </th> <th>NOME PROCESSO</th> <th>HOST</th>{' '}
            <th>ANDAMENTO</th> <th>DURATA</th> <th>AVANZAMENTO</th>{' '}
          </tr>
        </thead>
        <tbody>
          <tr>
            <td> {date} </td>{' '}
          </tr>
        </tbody>
      </table>
    </div>
  );
}



 
© www.soinside.com 2019 - 2024. All rights reserved.