簡體   English   中英

如何基於 AJAX 渲染導致反應 js?

[英]How to render based on AJAX result in react js?

只想根據來自 ajax 調用的結果渲染電影卡。

目前,電影卡組件是基於名為 list 的硬代碼數組呈現的。 我只想讓它動態化並用我的 ajax 數據替換它。

const getlist = async () => {
  const res = await fetch('http://localhost:3001/customize');
  const data = await response.json();
  getlist();
};

export default function Index() {

  const list = ['dexter', 'bb', 'got'];

  return (
    <>
      <main className={parentstyle.main_container}>
        <NavBar />
        <div className={style.searchbar_container}>
          <SearchBar />
        </div>
        <div className={style.card_container}>
          {test.map((element, i) => {
            return <MovieCard movieName={element} key={i} />;
          })}
        </div>
      </main>
    </>
  );
}

使用useState掛鈎設置您的組件 state(列表)並在useEffect掛鈎中獲取數據...

Effect Hook 允許您在 function 組件中執行副作用:

在 React 組件中獲取數據、設置訂閱以及手動更改 DOM 都是副作用的示例。 無論您是否習慣將這些操作稱為“副作用”(或僅稱為“效果”),您之前都可能在組件中執行過它們。

import { useEffect, useState } from "react"

const getlist = async () => {
  const res = await fetch("http://localhost:3001/customize")
  if (!res.ok) {
    throw new Error(`${res.status}: ${await res.text()}`)
  }
  return res.json()
}

const Index = () => {

  const [ list, setList ] = useState([]) // start with an empty array

  useEffect(() => {
    getList()
      .then(setList)
      .catch(console.error)
  }, []) // empty dependencies array, this runs only once

  return (
    // ...

    {list.map((element, i) => (
      <MovieCard movieName={element} key={i} />
    ))}

    // ...
  )
}

export default Index

暫無
暫無

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

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