在React JS中,可以通过使用React Router库来实现页面之间的导航和状态保存。React Router是React官方推荐的路由库,它可以帮助我们在React应用中实现页面之间的切换和导航。
要在React JS中保存以前的状态/页面数据并在转到另一个页面之前恢复,可以使用以下步骤:
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
</div>
</Router>
);
import { useState } from 'react';
const Home = () => {
const [count, setCount] = useState(0);
return (
<div>
<h1>Home</h1>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increase Count</button>
</div>
);
};
在上面的例子中,我们使用useState钩子来创建一个名为count的状态变量,并通过setCount函数来更新它。每次点击按钮时,count的值会增加,并在页面切换时保留下来。
领取专属 10元无门槛券
手把手带您无忧上云