可以从不同的JSX文件中访问另一个JSX组件的API数据吗?

huangapple go评论60阅读模式
英文:

Is it possible to access another jsx components api data from a different jsx file?

问题

以下是您要翻译的代码部分:

我使用 useEffect 构建了一个产品页面以从 API 获取信息然后进行映射

```javascript
 useEffect(() => {
    fetch("/api/artProducts.json")
      .then((response) => response.json())
      .then((data) => setArt(data));
  }, []);

          <div id="allList" className={`artList${category.category_id}`}>
            {category.art.map((art) => (
              <div key={art.art_id}>
                <div>
                  <h3>{art.name}</h3>
                  <img
                    src={art.image}
                    alt=""
                    onClick={() => getImg(art.image)}
                  />
                  <NavLink to={`/art-details/${art.art_id}`}>
                    <button type="button">order now!</button>
                  </NavLink>
                </div>
                <p>
                  price{" "}
                  <span>{String(art.price).replace(".", ",")}€</span>
                </p>
              </div>
            ))}
          </div>

但我想创建一个包含更多信息的产品详情页面,我不知道如何连接这两个页面。

我已经进行了大量的研究,这是我尝试的方式,但我只得到一个空白页面。

export default function ProductPage(props) {
  const [artDetails, setArtDetails] = useState([]);

  useEffect(() => {
    getResponse();
  }, []);

  const getResponse = async () => {
    const res = await fetch(`/api/galeria.json/${props.art.art_id}`).then(
      (res) => res.json()
    );

    setArtDetails(await res);
  };

  return (
    <section>
      <div>
        <h2>{artDetails.art.name}</h2>
      </div>
    </section>
  );
}
英文:

I built a product page using useEffect to get information from an API, and then mapping

 useEffect(() =&gt; {
    fetch(&quot;/api/artProducts.json&quot;)
      .then((response) =&gt; response.json())
      .then((data) =&gt; setArt(data));
  }, []); 

          &lt;div id=&quot;allList&quot; className={`artList${category.category_id}`}&gt;
            {category.art.map((art) =&gt; (
              &lt;div key={art.art_id}&gt;
                &lt;div&gt;
                  &lt;h3&gt;{art.name}&lt;/h3&gt;
                  &lt;img
                    src={art.image}
                    alt=&quot;&quot;
                    onClick={() =&gt; getImg(art.image)}
                  /&gt;
                  &lt;NavLink to={`/art-details/${art.art_id}`}&gt;
                    &lt;button type=&quot;button&quot;&gt;order now!&lt;/button&gt;
                  &lt;/NavLink&gt;
                &lt;/div&gt;
                &lt;p&gt;
                  price{&quot; &quot;}
                  &lt;span&gt;{String(art.price).replace(&quot;.&quot;, &quot;,&quot;)}€&lt;/span&gt;
                &lt;/p&gt;
              &lt;/div&gt;
            ))}
          &lt;/div&gt;

but I want to create a product details page with more information and I'm stuck on how to connect the two.

I have researched a lot of solutions, this is what I tried to do but all I get is a blank page.


export default function ProductPage(props) {
  const [artDetails, setArtDetails] = useState([]);

  useEffect(() =&gt; {
    getResponse();
  }, []);

  const getResponse = async () =&gt; {
    const res = await fetch(`/api/galeria.json/${props.art.art_id}`).then(
      (res) =&gt; res.json()
    );

    setArtDetails(await res);
  };

  return (
    &lt;section&gt;
      &lt;div&gt;
        &lt;h2&gt;{artDetails.art.name}&lt;/h2&gt;
      &lt;/div&gt;
    &lt;/section&gt;
  );
}

答案1

得分: 0

在第一页上,你正在获取 /api/artProducts.json,这似乎是服务器返回的一个实际的JSON文件,除非他们真的将路由命名为 /api/artProducts.json,但我怀疑这种情况。

所以很可能你在向后端服务器发送请求时格式不正确。这不是标准的API路由请求格式:

/api/galeria.json/${props.art.art_id}

你需要创建一种API路由,它可以接受 art_id 作为参数,然后执行一些后端逻辑,只返回与你的 art_id 相关的 galeria.json 中的结果。

一个示例的Express路由:

app.post('/api/galeria/:art_id', (req, res) => { ... });

然后在Express处理程序中,你可以使用 req.params.art_id 来访问 art_id

或者,如果你只想返回来自 /api/galeria.json 的所有结果,你可以在前端使用 art_id 进行结果筛选。大致如下:

const galeriaJSON = [
  { art_id: 1, text: 'hello darkness my old friend' },
  { art_id: 2, text: 'hello world' }
];

const filteredResults = galeriaJSON.filter((row) => {
  return row.art_id === props.art.art_id;
});
英文:

On the first page, you're fetching /api/artProducts.json which seems to be an actual JSON file the server is returning. Unless they literally named the route /api/artProducts.json which I doubt.

So then it seems very likely you're formatting your request to the backend server wrong. This is not a standard way of formatting an API route request:

/api/galeria.json/${props.art.art_id}

You need to create some sort of API route that simply handles taking the art_id as a parameter, then perform some backend logic to return only the results from galeria.json that are related to your art_id.

An example express route:

app.post(&#39;/api/galeria/:art_id&#39;, (req, res) =&gt; { ... });

Then within the Express handler you access art_id using req.params.art_id.

Or if you simply want to return all the results from /api/galeria.json, you can filter the results on the frontend using the art_id. Something along the lines of:

const galeriaJSON = [
  { art_id: 1, text: &#39;hello darkness my old friend&#39; },
  { art_id: 2, text: &#39;hello world&#39; }
];

const filteredResults = galeriaJSON.filter((row) =&gt; {
  return row.art_id === props.art.art_id;
});

huangapple
  • 本文由 发表于 2023年2月16日 02:06:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75463818.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定