React.js。如何仅显示获取的API的第一个对象?

I am trying to show only first object of API, which I succeed in console, but when I put it in useState, it gives me an error Parsing error: Unexpected token, expected "," here is my code, I guess I have a typo, but can't find

import Meme from "./Meme";

export default function App() {
  const [data, setData] = useState([]);

const fetchData  = () => {
  fetch("https://api.imgflip.com/get_memes")
  .then(res => res.json()) 
  .then(result =>{ setData(result.data.memes) /*.then(result =>{ setData(result.data.memes[0]<<-- this will give an error*/
  console.log(result.data.memes[0])
  }
  )
  .catch(err => console.log("error"))
  }

  useEffect(() => {
    fetchData()
  }, [])



  return (
    <div className="App">
   {data.map((element, index) => (
          <Meme
            key={index}
            title = {element.name} 
            image = {element.url}
          />
        ))}
    </div>
  );
}

```
评论
  • 有夫之夫
    有夫之夫 回复

    您可以更改此:

    setData(result.data.memes)
    

    至 :

    setData([result.data.memes[0]])
    

    要么

    如果您一直只需要第一个元素,就应该这样做   这个

    变更:

    const [data, setData] = useState([]);
    
    setData(result.data.memes)
    

    至 :

    const [data, setData] = useState({});
    
    setData(result.data.memes[0])
    

    要么

    您可以只使用渲染中的第一个元素。