Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

javascript - In React is it possible to avoid reloading data from server upon pressing browser back button (without using Redux)?

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Well, for (a) you can use Context API. It's similar to Redux so you can store state even when components are unmounted.

For (b) and (c), a possible approach would be to verify if the user went to the page by pressing back button. You can do something like:

const history = useHistory()
const [cameByBackButton, setCameByBackButton] = useState(false)

useEffect(() => {
  if (history.action === "POP") {
    setCameByBackButton(true);
  };
}, [history.action]);

So with cameByBackButton state you can identify if the back button was pressed and then you can use it to decide if a http call should be made or even if a component should be rendered.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...