React implements the method of remembering the page status before jumping: 1. Monitor path changes, and update lastPath and currentPath to the redux store when the path changes; 2. When leaving page A, save the page status to In the redux store; 3. If the lastPath in the redux store is equal to the path of page B, it is considered that A is returned to the restored state by B, otherwise it will not be restored.
The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.
How to remember the page status before jumping in react?
React page returns to retain the last state
Requirements
Page A jump Go to page B and then return to page A. Page A needs to restore the state before leaving;
There are multiple entrances to page A and page B. Jump to page A from other pages. Page A does not restore state.
##Design
Implementation
The project uses the react-router dva library, and the implementation part will involve related technologies. Monitor path changes, monitor path changes through history, and record lastPath and currentPath. Here, DVA subscriptions are used to subscribe to history, and when the path changes, the path information is synchronized to the state.const model = { namespace: "global", state: { pathName: { last: "", current: "" }, }, reducers: { setPathName(state: any, { pathName }: any) { state.pathName.last = state.pathName.current; state.pathName.current = pathName; }, effects: { }, subscriptions: { setup({ history, dispatch }: any) { return history.listen(({ pathName }: any) => { dispatch({ type: "global/setPathName", pathName }); }); } } };
componentWillUnmount() { const { dispatch } = this.props; const { activeKey } = this.state; dispatch({ type: "projectInfo/setProjectInfoPage", payload: { activeKey } }); }
state = { activeKey: pathToRegexp(PagePath.B).exec(pathName.last) ? activeKey : "" };
Other solutions
Judge whether page A is returned by page B: add state when page B returns, history.push({ pathname: path, state: {from } });, enter the A page and judge whether to return from the B page according to the state. But when B has multiple entrances, you need to know the source of the page when returning, otherwise you cannot return, and the logic is slightly complicated and error-prone.Summary
This article proposes a solution for page return to retain the last state, which is suitable for situations where the page has multiple entrances and exits. This solution uses the method of monitoring history changes and recording the last page address, thus providing a basis for whether to restore the state. Recommended learning: "react video tutorial"
The above is the detailed content of How to remember page status before react jump. For more information, please follow other related articles on the PHP Chinese website!