簡體   English   中英

如何在 reactjs 中將道具傳遞給其他組件

[英]How can I pass props to another components with in reactjs

我正在嘗試將產品數據從 AllProducts 組件傳遞到 Product 組件。

AllProducts.jsx :顯示我擁有的所有產品, Product.jsx將顯示特定產品,我如何將數據傳遞給Product.jsx

這是我的AllProducts.jsx

const AllProducts = (props) => {
  const [products, setProducts] = useState([]);

  const getProductsAPI = () => {
    axios
      .get("http://localhost:8000/api/products")
      .then((res) => {
        setProducts(res.data);
        getProductsAPI();
      })
      .catch((err) => {
        console.log(err);
      });
  };

  useEffect(() => {
    getProductsAPI();
  }, [props]);

  return (
    <div>
      <table className="table table-bordered table-hover">
        <thead>
          <tr>
            <th>#</th>
            <th>Title</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
          {products.map((product, i) => (
            <tr key={i}>
              <th scope="row">{i}</th>
              <td>{product.title}</td>
              <td>
                <Link to={`/products/${product._id}`}> View </Link>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

這是我的Product.jsx

const Product = (props) => {
  return (
    <div className="container">
      <h4>{props.product.title}</h4>
    </div>
  );
};

export default Product;

這是我的項目 github 如果您想查看我擁有的所有代碼: https://github.com/nathannewyen/full-mern/tree/master/product-manager

  • 如果 AllProducts 中每個產品的數據都已完全加載,並且您不想在 Product 組件中通過產品 id 進行另一個 API 調用,在這種情況下,您不必使用路由鏈接來查看 Product,只需進行條件渲染以顯示 AllProducts 組件內的 Product 組件。 偽代碼如下,

     const [showProduct, setShowProduct] = useState(false); const [currentProduct, setCurrentProduct] = useState(); const showProduct = (product) => { setShowProduct(true); setCurrentProduct(product); } <tbody> {products.map((product, i) => ( <tr key={i}> <th scope="row">{i}</th> <td>{product.title}</td> <td> <button type="button" onclick = {showProduct(product)}>View</button> </td> </tr> ))} </tbody> return (showProduct? <Product />: <AllProucts/>)
  • 如果您還需要進行另一個 API 調用以獲取每個產品的額外數據,則使用路由器鏈接但可能無法傳遞道具。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM