My React app uses CRA with react-router for routing.
After rendering this component if the user goes to another page this component gets un-mounted. When the user navigates back to it using the browser back button, the component is re-mounted and fetches the data form the server again.
I fully understand why this is happening and that it's the expected behaviour.
However, what's the best way to change my setup so that:
(a) the state persists after leaving the page (un-mounting the component), and
(b) the state is reloaded from server if user comes to the page through other than the browser back button
(c) the app knows whether a render is triggered by browser back button or not
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])
As far as I understood Redux supports this use case? What would be the best way to reflect this without implementing Redux?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…