const ViewCategory = () => {
const history = useHistory();
useEffect(() => {
axios
.get("http://localhost:8080/products", {
headers: {
Authorization: "Bearer " + localStorage.getItem("token"),
},
})
.then((response) => {
console.log("List of products", response.data);
setData(response.data);
setisLoaded(true);
})
.catch((error) => {
console.log(error);
});
}, []);
const [data, setData] = useState();
const [isloaded, setisLoaded] = useState(false);
const viewProductVariation = (productId) => {
history.push("/ProductVariation", {
productId,
});
};
let products = null;
if (isloaded) {
products = data.map((product) => (
<div className="card">
<div class="col-sm">
<div className="card-body">
<h4 className="card-title"> {product.name} </h4>
<p className="card-text"> {product.brand} </p>
<button
className="btn btn-primary"
onClick={() => viewProductVariation(product.id)}
>
View
</button>
</div>
</div>
</div>
));
}
return (
<div className="container">
<div className="row"> {products} </div>
</div>
);
};
useEffect(() => {
const Id = props.history.location.state?.productId;
axios
.get("http://localhost:8080/productVariationDisplay/" + Id, {
headers: {
Authorization: "Bearer " + localStorage.getItem("token"),
},
})
.then((response) => {
console.log("List of products variation", response.data);
setData(response.data);
})
.catch((error) => {
console.log(error);
});
}, []);
我是反应钩子的新手,我正在尝试使用反应钩子将 viewProductVariant 的产品 ID 传递给另一个组件,但我遇到了一个问题,我得到了未定义的道具,谁能告诉我如何使用反应钩子使用可选处理将该 productId 从一个组件传递到另一个组件
您可以使用目标组件中的路由器挂钩useParams()
来获取参数值
const { productId } = useParams();