English 中文(简体)
下一步 Js 使用效应触发器在每条路线上都会发生。
原标题:NextJs useEffect triggers every time I route

我正在建造一个下游 b。

在目前的博客布局中,我通过使用效应/fetch(因为只用页页处理)在我的侧厅上收集了数据(我需要显示我的“重要职位”),但每页之间的路段,都会触发数据。 (一) 空白处,并重载职位头衔)

是否有办法在最初的负荷后消除这种行为,并造成一种固定或冷静? 我使用了“[]”方法,但至今没有uck子:

  const [posts, setPosts] = useState([])

  useEffect(()=>{
    const fetchData = async () => {
      const res = await fetch( /api/posts );
      const {data} = await res.json();
      setPosts(data)
    }
    fetchData()
  }, []);

还是有更好的办法在我的侧厅收集数据? 这是我设法使之发挥作用的唯一解决办法,但它是半工作。

问题回答
import { useState, useEffect } from  react 


export default function RightBar() {

  const [posts, setPosts] = useState([])

  useEffect(()=>{
    const fetchData = async () => {
      const res = await fetch( /api/posts );
      const {data} = await res.json();
      setPosts(data)
    }
    fetchData()
  }, []);


    return (
      <div className="rightbar content">
        <div className="rightbarContent">
          <h3 className="sidebarborder"><span className="sidebarheader">Recent Posts</span></h3>
          {posts.slice(0,5).map(posts => {
              return (
                <div key={posts._id}>
                    * <Link href={`/${posts._id}`}>{posts.title}</Link>
                </div>
              )
          })}
          <h3>Categories</h3>
          <p>blabla</p>
        </div>      
      </div>
    )
  }

The component layout is this:

Layout > Header Topnav Mainfooter

Main has 2 children > LeftBar (where my main content resides) and RightBar (where I show my recent posts)

Layout总结了索引页。 因此,我转授了孩子们的主食;左侧部分。

我希望这一解释是充分的。





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签