[英]In React is it possible to avoid reloading data from server upon pressing browser back button (without using Redux)?
我的 React 应用程序使用 CRA 和 react-router 进行路由。
如果用户转到另一个页面,则在渲染此组件后,此组件将被卸载。 当用户使用浏览器返回按钮导航回它时,该组件被重新安装并再次从服务器获取数据。
我完全理解为什么会发生这种情况,这是预期的行为。
但是,更改我的设置的最佳方法是什么:
(a) state 在离开页面后仍然存在(卸载组件),并且
(b) 如果用户通过浏览器后退按钮以外的方式进入页面,则 state 将从服务器重新加载
(c) 应用程序知道渲染是否由浏览器后退按钮触发
const TableView = ({ view, module }) => {
const [isLoading, setIsLoading] = useState(true)
const [records, setRecords] = useState([])
useEffect(() => {
console.log("Mounting TableView")
return () => {
console.log("Un-Mounting TableView")
}
}, [])
useEffect(() => {
let mounted = true;
module.getAll() // gets data from server
.then(res => {
if (mounted) {
setRecords(res);
setIsLoading(false);
}
})
.catch(alert)
return () => mounted = false
}, [module])
据我了解 Redux 支持这个用例吗? 在不实施 Redux 的情况下反映这一点的最佳方法是什么?
好吧,对于(a) ,您可以使用Context API 。 它与 Redux 类似,因此即使在卸载组件时也可以存储 state。
对于(b)和(c) ,一种可能的方法是验证用户是否通过按下后退按钮进入页面。 您可以执行以下操作:
const history = useHistory()
const [cameByBackButton, setCameByBackButton] = useState(false)
useEffect(() => {
if (history.action === "POP") {
setCameByBackButton(true);
};
}, [history.action]);
因此,使用cameByBackButton
state 您可以识别是否按下了后退按钮,然后您可以使用它来决定是否应该进行http调用,或者是否应该渲染组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.