English 中文(简体)
我如何利用Params(Params)在React的初期阶段进行过滤,而不是提出另一个要求?
原标题:How can I useParams() to filter over initial state in React, instead of making another get request?

这是我的第一个问题,请与我一起回答。 I m从事一项SPA React项目,该项目跟踪农场及其相关床位,并可使用一些帮助。 我愿通过用Params(Params)(而不是向农场/农场(id)提出更多的要求,对最初的州进行过滤,从而提供有关农场尾页的一些数据。 我已提出1英寸的请求,并在所有护堤变量中挽救了最初状态。 我用回旋-地把一些链接带走,利用被点击的农场的id走一条道路。

迄今为止,该构成部分已翻了两番,在第二次通过时,我使用的log(农场)确实产生了正确的农田。 从那时起,由于I m没有确定国家,而该构成部分已经使回报值变得空白,从农场={}起,它就不再保留。

import { useParams } from "react-router-dom";

function FarmDetail({ allFarms, setAllFarms }) {
  console.log("render");

  let { id } = useParams();
  id = parseInt(id);

  let farm = {};

  useEffect(() => {
    if (allFarms) {
      farm = [...allFarms].find((f) => f.id === id);
    }
    console.log(farm);
  }, [allFarms]);

  console.log(farm);
  console.log(allFarms);

  return (
    <div>
      <p>{farm.name}</p>
    </div>
  );
}

export default FarmDetail;

我试图将国家用于农田变数,并设定使用国,以引发再耕,但随着农场被设定为不明确,我从来不会引发使用的效果。 所有的护堤也只是一片空洞,我不明白为什么。 我最后看着一种类型错误:不能读到对我来说具有意义的未经界定的特性(“名称”),因为农场仍然未如此界定。 我感到很接近,但我在这里没有东西。 任何帮助都受到高度赞赏!

问题回答

I saw your code. And I am agree with Phil s answer. You can use useMemo hook instead of 使用效果. And by the way, the reason, you component renders twice, is that first your component renders (with initial allFarms data) sencod your component renders (with fetched allFarms data)

因此,你的构成部分造成空白,是你提到:

let farm = {};

inside your component. So every re-render, farm will initialized as blank {} but

使用效果

只有在所有护堤变数发生变化时,才算起。

希望这一答案有助于。





相关问题
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.

热门标签