我如何使用 React link 购物页面中的商品列表和商品

How do i link Goods List & Goods in shopping page with React

我正在用 React 制作购物页面。

我想点击商品图片进入详情页

我试图通过 /goods/${id}}> 获取点击我的商品 ID GoodsList 代码中的此代码。

然后,在 GoodsDetail 代码中,我试图获取我喜欢的商品 ID 并呈现商品数据

但是GoodsList中的代码好像不太好用

当我点击商品图片时,页面没有转到商品/{id},而是转到goods/undefined。

如何修复我的代码?

这是App.js代码

import React from 'react';
import './App.css';
import Navbar from './components/Navbar';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './pages';
import Sell from './pages/sell';
import Search from './pages/search';
import AboutMe from './pages/aboutme';
import Login from './pages/login';
import TradeRecord from './pages/traderecord';
import SignUp from './pages/signup';
import Zzim from './pages/zzim';
import Selling from './pages/selling';
import Goods from './pages/goods';


const App = () => {
  
  return (
    <div className='App'>
      <BrowserRouter>
       <Navbar />
          <Routes>
            <Route path="/" element={<Home />}></Route>
            <Route path="/sell" element={<Sell />}></Route>
            <Route path="/search" element={<Search />}></Route>
            <Route path="/signup" element={<SignUp />}></Route>
            <Route path="/login" element={<Login />}></Route>
            <Route path="/aboutme" element={<AboutMe />}></Route>
            <Route path="/selling" element={<Selling />}></Route>
            <Route path="/zzim" element={<Zzim />}></Route>
            <Route path="/traderecord" element={<TradeRecord />}></Route>
            <Route path="/goods/:id" element={<Goods />}></Route>
          </Routes>
      </BrowserRouter>
    </div>
  )
}

export default App;

这是商品列表页面代码

import React, {useState, useEffect} from 'react';
import { Link, useParams } from 'react-router-dom';
import axios from 'axios';
import './index.css';

const SearchView  = (props) => {
    const [boards, setBoards] = useState([]);
    const {id} = useParams();
  
  useEffect(() => {
    (async function () {
      const response = await axios.get("https://27.96.131.85:8443/api/boards")
        .catch((err) => {
          console.log(err);
        });
      const boards = response.data;
      
      setBoards(boards);
      console.log(response.data);
    })();
  }, []);

    return(
        <div>
            <hr />
            <div id='product-list'>
                {
                    boards.map(function(boards, index){
                        return (
                            <div className='product-card'>
                                <Link className='product-link' to={`/goods/${id}`}>
                                    <div>
                                    {
                                    boards.boardImages[0]
                                    ? <img className="product-img" width="100" height="100"
                                      src={`https://27.96.131.85:8443/api/images/${boards?.boardImages[0]?.id}`} />
                                    : <img className="product-img" width="100" height="100" src={require("../../images/noImage.png")} />  
                                    }                                 
                                    </div>
                                    <div className='product-contents'>
                                        <span className='product-name'>
                                            {boards.goodsName}
                                        </span>
                                        <span className='product-price'>
                                            {boards.price}원
                                        </span>
                                        <div className='product-seller'>
                                            <span>{boards.writer}</span>
                                        </div>
                                    </div>
                                </Link>
                            </div>
                        )
                    })
                }
            </div>
         </div>
    );
};

export default SearchView;

这是商品详情代码

import { useParams } from "react-router-dom";
import axios from "axios";
import { useEffect, useState } from "react";

const Goods  = (props) => {
  const [boards, setBoards] = useState({});
  const [images, setImages] = useState([]);
  const {id}  = useParams();

  useEffect(() => {
    (async function () {
      const response = await axios.get(`https://27.96.131.85:8443/api/boards/${id}`, {
        withCredentials: true,
      });
      const boards = response.data;
      const images = boards.boardImages;
      console.log(response.data);

      setBoards(boards);
      setImages(images);

    })();
  }, []);

    return(
      <div id="product">
      상품명: <span className="product-name">{boards.goodsName}</span>
      <br />
      가격: <span className="product-price">{boards.price}원</span>
      <div className="product-seller">
        작성자: <span>{boards.writer}</span>
      </div>
      <div className="product-isSale">
        판매여부: <span>{boards.sale?.toString()}</span>
      </div>
      <div className="product-isLiked">
        찜 여부: <span>{boards.liked?.toString()}</span>
      </div>
      <div className="product-atCreated">
        작성 시간: <span>{boards.createdDateTime}</span>
      </div>
      <div className="product-atModified">
        수정 시간: <span>{boards.modifiedDateTime}</span>
      </div>
      <div className="product-images">
        {
          images.map((image) => {
            return (
              <img className="product-img" width="100" height="100"
                src={`https://27.96.131.85:8443/api/images/${id}`} />
            )
          })
        }
      </div>
    </div>
    );
};

export default Goods;

我觉得应该是boards.id,而不是id..

<Link className='product-link' to={`/goods/${id}`}>

能否分享一下你的数据结构?

您的商品列表页面代码有误,

解决方案:

{boards.map(function (boards, index) {
    return (
      <div className="product-card">
        <Link className="product-link" to={`/goods/${boards.id}`}>
          <div>
            {boards.boardImages[0] ? (
              <img
                className="product-img"
                width="100"
                height="100"
                src={`https://27.96.131.85:8443/api/images/${boards?.boardImages[0]?.id}`}
              />
            ) : (
              <img
                className="product-img"
                width="100"
                height="100"
                src={require("../../images/noImage.png")}
              />
            )}
          </div>
          <div className="product-contents">
            <span className="product-name">{boards.goodsName}</span>
            <span className="product-price">{boards.price}원</span>
            <div className="product-seller">
              <span>{boards.writer}</span>
            </div>
          </div>
        </Link>
      </div>
    );
  })}

当您使用 map 函数遍历 boards 数组时, 并且您已将变量名称 'boards' 分配给数组的每个元素 所以变量 boards 本身是一个包含 id 属性.

的对象

所以你必须写 boards.id 来解决你的问题

希望对您有所帮助