简体   繁体   中英

React pass fetched data from API to another component

I am fetching few products from an API, and displaying them in card. There is a More Details link on the cards, where if the user clicks on it, it will take the user to the selected product details page. My routing to productDetails page works, But I am having troubles to find a way to pass the fetched data to the productDetails page as props.

import React from "react";
import { useState, useEffect } from "react";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
import ProductDetails from "./ProductDetails";
import axios from "axios";

function FeaturedProduct(props) {
  const [products, setProducts] = useState([]);
 
  useEffect(() => {
    fetchProducts();
  }, []);

  function fetchProducts() {
    axios
      .get("https://shoppingapiacme.herokuapp.com/shopping") 
      .then((res) => {
        console.log(res); 
        setProducts(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  }
  return (
    <div>
      <h1> Your Products List is shown below:</h1>
      <div className="item-container">
       
        {products.map((product) => (
          <div className="card" key={product.id}>
            {" "}
           
            <h3>{product.item}</h3>
            <p>
              {product.city}, {product.state}
            </p>
            <Router>
              <Link to="/productdetails">More Details</Link>

              <Switch>
                <Route path="/productdetails" component={ProductDetails} />
              </Switch>
            </Router>
          </div>
        ))}
      </div>
    </div>
  );
}

export default FeaturedProduct;

I am still learning but this is what I would do:

<Route path="/productdetails">
  <ProductDetails product={product}/>
</Route>

====

On ProductDetails you can destructure the props:

function ProductDetails(props) {
const {name, color} = props.product;

  return (
    <div>
      <div>
        <h1>{name}</h1>
        <h1>{color}</h1>
      </div>
    </div>
  );
}
export default  ProductDetails;

Pass it as an element with props, if you are using v 6; sorry I didn't ask which version. >

<Switch>
<Route path="/productdetails"  element={<ProductDetails {...props} />}/>
</Switch>

if version v4/5 use the render method >

<Route path="/productdetails" render={(props) => (
{ <ProductDetails {...props} />} )}/>
 //pass it this way
 <Switch>
   <Route 
   path="/productdetails" 
   render={() => (
   { <ProductDetails  product={product}/>})}/>
   />
  </Switch>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM