UseEffect API 请求在页面加载时不显示

如果类似问题已经得到解答,请提前致歉。我已经尝试了一切,但仍然无法弄清楚为什么我会遇到这个小错误。我希望 Firestore 中的推文集合在加载时呈现在页面上。现在,只有在我发出发布请求后才会发生。


这是我的要求


useEffect(() => {

  const getTweets = async () => {

    const tweets = await firestore.collection('tweet').get();

    tweets.forEach(doc => {

    results.push(doc.data());

    })

  }

  getTweets()

}, [])


这是我将其映射到页面的位置:


return (

    <>

      <main className="tweet-container">

        <div className="tweet-container--content">

          {results.map((tweet, index) => (

            <InputResults

            key={index}

            tweet={tweet}

            />

            ))}

        </div>

      </main>

    </>

  )

}


POPMUISE
浏览 78回答 2
2回答

吃鸡游戏

尝试这样的事情,import React, {useState, useEffect} from "react";function App() {&nbsp;&nbsp;&nbsp; &nbsp; const [results, setResults] = useState([]);&nbsp; &nbsp; useEffect(() => {&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; const getTweets = async () => {&nbsp; &nbsp; &nbsp; &nbsp; const tweetsData = [];&nbsp; &nbsp; &nbsp; &nbsp; const tweets = await firestore.collection('tweet').get();&nbsp; &nbsp; &nbsp; &nbsp; tweets.forEach(doc => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tweetsData.push(doc.data());&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; setResults(tweetsData);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; getTweets()&nbsp; &nbsp; }, [])&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; &nbsp; <main className="tweet-container">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div className="tweet-container--content">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {results.map((tweet, index) => (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<h1>{tweet}</h1>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ))}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; </main>&nbsp; &nbsp; &nbsp; </>&nbsp; &nbsp; )}参考: https:&nbsp;//reactjs.org/docs/hooks-state.html

蓝山帝景

当使用地图函数在 UI 上显示元素时,请始终向元素添加关键属性。因为它有助于做出反应以区分元素。return (&nbsp; &nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; &nbsp; <main className="tweet-container">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div className="tweet-container--content">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {results.map((tweet, index) => (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<h1 key={index}&nbsp; >{tweet}</h1>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ))}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; </main>&nbsp; &nbsp; &nbsp; </>&nbsp; &nbsp; )
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript