Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

javascript - How prevent multiple client-side rerendering in Next.js (latest version)

I'm fetching some data from a geocoding API (HERE) in my ContextProvider. Then I use that data inside the underneath posted component:

const Results = memo(() => {
  const {
    userLng,
    userLat,
    marke,
    modell,
    buyRent,
    umkreis,
    query,
  } = useContext(IndexContext)

  const results = items.filter(
    (i) =>
      (haversineDistance([userLat, userLng], [i.lat, i.lng]) <= umkreis ||
        umkreis === 'egal') &&
      (i.marke.toLocaleLowerCase() === marke ||
        marke === '' ||
        marke === 'egal') &&
      (i.modell.toLocaleLowerCase() === modell ||
        modell === '' ||
        modell === 'egal') &&
      ((i.buy === true && buyRent === 'kaufen') ||
        (i.rent === true && buyRent === 'mieten'))
  )

  console.log(results)

  if (query === '') {
    return <InitialPage />
  } else if (results.length !== 0) {
    return (
      <>
        {results.map((i) => {
          return (
            <div key={uuid()} className="border mt-4">
              <Result
                marke={i.marke}
                modell={i.modell}
                query={query}
                userLat={userLat}
                userLng={userLng}
                lat={i.lat}
                lng={i.lng}
              />
            </div>
          )
        })}
      </>
    )
    // dieser code sollte erst ausgeführt werden wenn obiges scheitert :/ - hinbekommen!
  } else if (results.length === 0) {
    return <p>NOTHING FOUND</p>
  }
})

export default Results

What the code is doing:
Based on the user's Input there are either results displayed or not. If there is no result for a query, then I want to simply display NOTHING FOUND.

The problem:
On the first page load the console logs:
[ ]
This is expected

After inserting a query for the FIRST TIME the console logs:
[ ]
[ ]
[ {...}, {...}, ... ]
This is not expected and my goal is to only log [ {...}, {...}, ... ] without the two preceding [ ]
BECAUSE by that the users see the message NOTHING FOUND for a short time until the array is filled (the 3rd console log).

When inserting another query after the first one, the behavior is as expected and no empty arrays appear in the console.

Can someone help please ?? as you can see I already tried memo but it has no effect.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...