[英]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.