React - 刷新后如何保留页面 url?

在我的 React 应用程序中,我已根据单击的页面名称将相应的页面名称存储在本地存储中,即对于一条路线来说,每当我单击 Products 页面时,我都会将http://localhost:3000/Products名称Products存储在本地存储中。


我希望每当我有一个页面刷新时,而不是被重定向到主页/,我的页面通过确认我的本地存储中的值而保留在我所在的页面上。


我的方法行不通。


<NavLink to="/localStorage.getItem("selectedItem")" style={{ textDecoration: "none" }}>

   <MenuItemComponent

       title="Products"

       icon={IconProducts}

       onClick={() => this.onItemClicked("Products")}

       active={localStorage.getItem("selectedItem") === "Products"}

    />

</NavLink>

从上面的代码中,我希望页面将我引导到,http://localhost:3000/Products因为localStorage.getItem("selectedItem")的值是Products


慕森王
浏览 116回答 1
1回答

www说

您需要从 LocalStorage 获取值,但您使用的是纯字符串。应该是这样的:const AppNaVLink = () => {&nbsp; &nbsp; const link = `/${localStorage.getItem("selectedItem") ?? ''}`&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <NavLink to={link} style={{ textDecoration: "none" }}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <MenuItemComponent&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; title="Products"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; icon={IconProducts}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onClick={() => this.onItemClicked("Products")}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; active={localStorage.getItem("selectedItem") === "Products"}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; &nbsp; </NavLink>)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript