簡體   English   中英

在 react 中訪問 RESTful API

[英]access to RESTful API in react

I have laravel in server side, that can show api with entering this url: http://localhost:8000/api/cabangs , and show this (the data as example):

[
 {
  "id":2,
  "nm_cabang":"zxcvb",
  "deskripsi":"poiuyt",
  "created_at":"2020-08-08T05:25:31.000000Z",
  "updated_at":"2020-08-08T05:29:23.000000Z"
 },
 {
  "id":3,
  "nm_cabang":"asdfg",
  "deskripsi":"qwerty",
  "created_at":"2020-08-08T05:28:26.000000Z",
  "updated_at":"2020-08-08T05:28:26.000000Z"
 }
]

我只想顯示nm_cabangdeskripsi 如果可能的話,使用react hooks 謝謝

使用 axios 或 fetch 之類的庫,您只需向 url 發出 http 請求並使用您需要的數據。

https://github.com/axios/axios https://javascript.info/fetch

我喜歡 axios

你可以從這樣的事情開始。 我假設這是針對 web 的,所以我使用了spandiv

const App: React.FC = () => {
  const [data, setData] = React.useState();
  const [isLoading, setLoading] = React.useState(true);

  React.useEffect(() => {
    const fetchData = async () => {
      try {
        const result = await fetch('http://localhost:8000/api/cabangs');
        if (result.ok)
        {
            let json = await result.json();
            setData(json);
        }
      } catch (e) {
        //error
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, []);

  if (isLoading) {
    return <span>Loading...</span>;
  }

  return (
    <div>
      {
      data ? (
        data.map((item) => {
          return <span>{`${item.nm_cabang} ${item.deskripsi}`}</span>;
        })
      ) : (
        <></>
      )
      }
    </div>
  );
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM