我有一个username属性,已使用它从“登录”路由传递到“产品列表”路由
return <Redirect to={{
pathname: "/products",
state: username
}}/>
然后我有一个 <Link to={'/products/${product.id}'}>More info</Link>将我从“产品列表”发送到“单个产品”的方法。
当我返回“产品列表”时<Link to={'/products'}>Back</Link>,用户名消失了。有没有办法保留用户名,以便当用户登录并在路线之间来回移动时,它会继续被存储?
这是我希望存储用户名的“产品列表”路线的完整代码:
import React, {useState, useEffect} from 'react';
import './Products.css';
import {Link} from 'react-router-dom';
function Products(props) {
const [products, setProducts] = useState([]);
useEffect(() => {
const fetchProducts = async () => {
const data = await fetch("https://example.com/products");
const products = await data.json();
console.log(products);
setProducts(products);
};
fetchProducts();
}, []);
let username = props.location.state;
return (
<div>
<p className = "HelloUser">Hello, {username}</p>
<p className = "ProductTitle">Our Selection</p>
<div className = "ProductGrid">
{products.map(product =>(
<div className = "ProductBox" key={product.id}>
<img className ="ProductImage" src={product.image} alt="did not load"/>
<p className ="ProductName">{product.name}</p>
<p className ="ProductDiscountedPrice">{"£" + (Math.round(product.discountedPrice * 100) / 100).toFixed(2)}</p>
<p className ="ProductPrice">{"£" + (Math.round(product.price * 100) / 100).toFixed(2)}</p>
<Link to={`/products/${product.id}`} className="MoreInfoButton">More info</Link>
</div>
))}
</div>
</div>
)
}
export default Products;
喵喔喔
相关分类