【问题标题】:Sending data through Components通过组件发送数据
【发布时间】:2021-04-11 05:09:37
【问题描述】:

我遇到了无法解决的问题。所以基本上我这里有 2 个组件 Component A 和 Component G 我有更多,但它们几乎相同(概念相同)。我在组件 G、A 中有一个链接,当我单击它时,它会将我带到支付组件。 Tt 现在将(ImageA、ClassA 和 PriceA)呈现为硬编码。无论如何,我想要实现的是,例如,当我单击组件 G 时,它只会呈现(imageG、classG 和 priceG),所以我需要它以某种方式过滤它或以某种方式在我想象的 json 文件中拆分数据,但我不知道该怎么做。我希望你们中的一位同志能帮助我。

Payment Component

const Payment = ({
  history,
  location: { state },
  match: {
    params: { dataId }
  }
}) => {
  if (!state?.postData) {
    history.goBack();
  }

  const { postData } = state;

  return (
    <div className="ml-20">
      <img
        alt=""
        className="w:2/4 object-contain "
        src={postData.imageG}     
        />
      <h2
        className=" ml-24 mlg:ml-6 mlg:mt-2 mlg:static text-5xl mlg:text-2xl text-blue-400 absolute top- 
        48"  >
        {postData.classG}
      </h2>
      <h3
        className="text-lg  mlg:mb-2 mlg:ml-6  mlg:mt-2 mlg:static font-bold text-green-800 
                 font-mono ml-24 top-64  absolute"
      >
        {postData.priceG}
      </h3>
    </div>
  );
};

export default Payment

A COMPONENT
import React from "react";
import data from "../data.json";
import { Link } from "react-router-dom";

function A() {
  return (
    <div className='bg-black '>
{data.filter(d =>
  d.classA &&
  d.imageA &&
  d.priceA)
  .map((postData) => {
        return (
          <div className='bg-black'  key={postData.id} >
            <div className='bg-black '>            
              <img
                alt=""
                className="w-full object-contain "
                src={postData.imageA}
              ></img>
              <h1 className=" ml-24 mlg:ml-6 mlg:mt-2 mlg:static text-5xl mlg:text-2xl text-red-600 
                  absolute top-48">
                  {postData.classA}
              </h1>
              <h1 className="text-lg  mlg:mb-2 mlg:ml-6  mlg:mt-2 mlg:static font-bold text-yellow-600 
                  font-mono ml-24 top-64  absolute" >
                  {postData.priceA}
              </h1>
              <Link
                to={{pathname: `/payment/${postData.id}`,
                state: {
                  postData,
                },
              }}
                className="py-1 px-2  mlg:ml-6 mlg:mt-14 mlg:static text-black-600 h-8  ml-24  top-72 bg- 
                white w-32 text-center text-gray-red
                rounded-full focus:outline-none focus:ring-2 focus:ring-gray-600 absolute" 
              >
                Buy Now
              </Link>

             </div>
               </div>
                 </div>
                )
                 }
export default A

G Component
import React from "react";
import data from "../data.json";
import { Link } from "react-router-dom";

function G() {
  return (
    <div className='bg-black '>
{data.filter(d =>
  d.classG &&
  d.imageG &&
  d.priceG)
  .map((postData) => {
        return (
          <div className='bg-black'  key={postData.id} >
            <div className='bg-black '>            
              <img
                alt=""
                className="w-full object-contain "
                src={postData.imageG}
              ></img>
              <h1 className=" ml-24 mlg:ml-6 mlg:mt-2 mlg:static text-5xl mlg:text-2xl text-red-600 
                  absolute top-48">
                  {postData.classG}
              </h1>
              <h1 className="text-lg  mlg:mb-2 mlg:ml-6  mlg:mt-2 mlg:static font-bold text-yellow-600 
                  font-mono ml-24 top-64  absolute" >
                  {postData.priceG}
              </h1>
              <Link
                to={{pathname: `/payment/${postData.id}`,
                state: {
                  postData,
                },
              }}
                className="py-1 px-2  mlg:ml-6 mlg:mt-14 mlg:static text-black-600 h-8  ml-24  top-72 bg- 
                white w-32 text-center text-gray-red
                rounded-full focus:outline-none focus:ring-2 focus:ring-gray-600 absolute" 
              >
                Buy Now
              </Link>

             </div>
               </div>
                 </div>
                )
                 }
export default G

Json file

[
   {
    "id":0,
    "classG":"G-Class",
    "imageG":"./ModImages/Gclass.jpg",
    "priceG":"Starting at $154,900",
     "newG":"A 12.3-inch digital gauge cluster is newly standard across the 
     board, as are heated front seats. Plus, the sedan can be had with a Night 
     package that adds black exterior trim.",
    "imageGIn":"./ModImages/GclassIn.jpg",
    "imageCOut":"./ModImages/GclassOut.jpg",
    "infoDesignC1":"How many technological breakthroughs can you fit into a C- 
    Class? With the advanced, powerful and sporty 2020 C 300 Wagon, plenty. From 
    its LED headlamps to its generous cargo hold, you'll find countless 
    refinements, and so many reasons it's a wagon like no other.",
    "infoDesignG" :"The acclaimed C-Class cabin is as functional as it is 
    beautiful. Abundant innovations harmonize with five options in hand-finished 
    wood trim. A 12.3-inch digital instrument cluster and 10.25-inch centre 
    screen are available.",
    "imageGIn1":"./ModImages/CclassIn1.jpg",
    "imageGOut1":"./ModImages/CclassOut1.jpg",
    "infoDesign2": "The Star on the outside is earned on the inside. The roomy, 
    refined cabin includes heated front seats and a driver-seat memory. Dual- 
    zone, double-filtered climate control. A panoramic sunroof. And options from 
    Burmester® surround sound to new Climate Comfort front seats.",
    "infoInov": "Available Apple CarPlay™ and Android Auto let you enjoy more 
    from your own smartphone. Another navigation option is COMAND, which brings 
    you voice control not only for navigation and audio, but also many cabin 
    features.",
    "imageInov1":"./ModImages/GclassInov1.jpg",
    "imageInov2":"./ModImages/GclassInov2.jpg",
    "infoInov1": "Available wireless charging lets you refuel your compatible 
     phone's battery as you drive. Easy-connect NFC pairing links your phone 
     every 
     time you get in. Apple CarPlay™ and Android Auto are available, too. And 
     four USB-C ports are standard.",
    "infoInov2": "DYNAMIC SELECT lets you fine-tune your A-Class with the tap of 
     a console button. Four modes vary shift points, throttle response, steering 
     feel and more: efficient ECO, everyday Comfort, sharpened Sport, and create- 
     your-own Individual.",
    "imageInov":"./ModImages/GclassInov.jpg",
    "imageInov4":"./ModImages/GclassInov4.jpg" ,
    "infoInov4G": "From the everyday to the unexpected, Mercedes me connect helps 
     ease your way. You can control vehicle features from your smartphone 
     (including Remote Start), set up a service appointment, and more. You can  
     also add In-car Wi-Fi for a low monthly rate. ",
    "infoInov5C":"Available driver assists help de-stress driving, changing lanes 
    with a tap of your finger, and knowing to slow for a tollboth or exit. A 
    network of sensors keeps a constant lookout for danger ahead, even if it's 
    coming from behind."
   },

   {
    "id":1,
    "classA":"A-Class",
    "imageA":"./ModImages/Aclass.jpg",
    "priceA":"Starting at $54,900",
    "newA":"In addition to a new 18-inch wheel design, the 2021 A-class gains 
    standard blind-spot monitoring and an optional gesture control feature for 
    the MBUX infotainment system.",
    "imageAIn":"./ModImages/AclassIn.jpg",
    "imageAOut":"./ModImages/AclassOut.jpg",
    "infoDesignA":"A is for attention-getting. The clean lines, LED lighting and 
    aggressive stance of the A-Class Sedan are designed to capture admiring eyes. 
    Its ultramodern cabin and premium appointments aim to captivate its driver 
    and passengers for years to come.",
    "infoDesignA1" :"With 100% LED lighting standard, inside and out, the A-Class 
    shines day or night, coming or going, and staying, too. Options include 
    MULTIBEAM LED headlamps and 64-colour ambient cabin lighting.",
    "imageAIn1":"./ModImages/AclassIn1.jpg",
    "imageAOut1":"./ModImages/AclassOut1.jpg",
    "infoDesignA2": "The Star on the outside is earned on the inside. The roomy, 
    refined cabin includes heated front seats and a driver-seat memory. Dual- 
    zone, double-filtered climate control. A panoramic sunroof. And options from 
    Burmester® surround sound to new Climate Comfort front seats.",
    "infoInov": "A is for advanced. With the Mercedes-Benz User Experience 
    (MBUX), the A-Class drives a new generation of user-friendly tech. Quite 
    possibly the most capable, natural and intuitive speech interface from any 
    automaker, it's easy to learn because it learns you.",
    "imageInov1":"./ModImages/AclassInov1.jpg",
    "imageInov2":"./ModImages/AclassInov2.jpg",
    "infoInov1": "Available wireless charging lets you refuel your compatible 
     phone's battery as you drive. Easy-connect NFC pairing links your phone 
     every time you get in. Apple CarPlay™ and Android Auto are available, too. 
     And four USB-C ports are standard. Disclaimer[6] Disclaimer",
    "infoInov2": "DYNAMIC SELECT lets you fine-tune your A-Class with the tap of 
    a console button. Four modes vary shift points, throttle response, steering 
    feel and more: efficient ECO, everyday Comfort, sharpened Sport, and create- 
     your-own Individual.",
    "imageInov3":"./ModImages/AclassInov3.jpg",
    "imageInov4":"./ModImages/AclassInov4.jpg" ,
    "infoInov4": "Get up close with the A-Class Sedan in this captivating ASMR audio experience. "
   }
]

【问题讨论】:

    标签: javascript json reactjs react-router


    【解决方案1】:

    我正在根据 cmets 更新答案

    首先,我会确保我的 JSON 属性在对象之间保持一致:

    [
       {
        "id":0,
        "class":"G-Class",
        "image":"./ModImages/Gclass.jpg",
        "price":"Starting at $154,900",
        "new":"Mercedes-Benz introduces a mid-cycle update of the E-class lineup for 2021. The changes 
         apply",
        "infoInov": "....",
        "imageOut": "..."
       },
    
       {
        "id":1,
        "class":"A-Class",
        "image":"./ModImages/Aclass.jpg",
        "price":"Starting at $54,900",
        "new":"Mercedes-Benz introduces a mid-cycle update of the E-class lineup for 2021. The changes 
         apply",
        "infoInov": "....",
        "imageOut": "..."
       }
    ]
    

    由于所有属性都是一致的,因此您可以始终如一地区分它们的唯一方法是通过 id 属性。如果id === 0,我们知道它是G。if === 1,我们知道它是A,等等。

    这样,我可以只使用一个组件来渲染它们。如果你想应用不同的样式或者渲染组件 G,你可以这样做:

    function AG() {
      return (
        <div className="bg-black">
          {data.map(product => (
             <div>
               <img src={product.image} />
               <h1>{product.class}</h1>
               <h1 className={product.id === 0 ? 'g-class' : ''}>{product.price}</h1>
               <Link to={`/payment/${product.id}` />
               {product.id === 0 && <div>This will only appear to G</div>}
             </div>
          ))}
        </div>
      )
    }
    

    请注意,我有一些检查以应用样式或仅在 product.id === 0 时渲染某些内容。这是重用组件并对其应用少量更改的方法之一。

    &lt;Link&gt; 中,我们将用户发送到/payments,并在路径中传递产品ID。所以在Payments 组件中,您将使用这个productID 来过滤来自JSON 的数据。

    现在在支付组件中,您只需导入相同的 JSON data 并通过我们在 URL 路径中传递的 id 进行过滤:

    import data from "../data.json"
    
    const Payment = () => {
      // get the id from the URL somehow, I suppose you are using react router
      // this is just an example
      const { idFromURL } = match.param
    
      const filteredProduct = data.filter(product => product.id === idFromURL)
    
      return (
        <div>
          <img src={filteredProduct.image} />
        </div>
      )
    }
    

    现在filteredProduct 变量包含 A 或 G 的数据,您可以使用它在 Payment 组件中显示您想要的特定数据。

    【讨论】:

    • 我已经更新了 json 文件。组件中的概念是相同的,但数据不是。这就是为什么我无法将所有内容从 json 提取到一个组件中,并且样式也不相同。
    • 我明白了。在我看来,拥有一个具有一致键的 JSON 文件将是一个很好的做法,因此您可以通过引用 id 属性来应用动态样式。比如,如果id === 0,应用一些className。但由于您可能无法做到这一点,您可以将data 导入您的支付组件并通过idFromURL 过滤数据。它对你有用吗?
    • 那我需要什么。我不明白你很抱歉
    • 我将通过一些我会采取的步骤来编辑我的答案,等一下 =)
    • 好了,如果还有困难,可以创建一个小repo,在这里分享,大家一起迭代
    猜你喜欢
    • 1970-01-01
    • 2018-06-15
    • 2016-10-28
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 2021-05-12
    • 2016-07-24
    • 1970-01-01
    相关资源
    最近更新 更多