reactjs 当用户访问其他路由时,如何清除redux状态?

yvgpqqbh  于 2023-01-02  发布在  React
关注(0)|答案(2)|浏览(234)

我有以下问题:我有一个通用组件,其中包含来自redux存储的一些数据,我希望在用户访问另一条路线时清除这些数据。

<Route path="/create/gallery" element={<CreatePage type={ContentType.gallery}/>} />

我也有一些更多的代码,保存我输入的数据到存储

saveGeneralInfo = (field: string, value: string) => {
        const data = {};
        data[field] = value;
        this.props.dispatch(saveGeneralInfo(data));
}

如果用户离开页面或访问任何其他链接,我如何清除状态?(例如从页眉)

if(this.state.keycloak) {
   if(this.state.authenticated) return (
      <div className="App">
           <Header/>
            <Routes>
                <Route path="/" element={<Content />} />
                <Route path="/sites"/>
                <Route path="/users"/>
                <Route path="/create/gallery" element={<CreatePage type={ContentType.gallery}/>}/>
                <Route path="/create/article" element={<CreatePage type={ContentType.article} />} />
                <Route path="/create/quiz" element={<CreatePage type={ContentType.quiz} />} />
             </Routes>
      </div>
                );
                else return (
                    <div>Can't authorize</div>
                )
            }
t2a7ltrp

t2a7ltrp1#

您必须在每个路由根组件中提供unMount生命周期事件触发的存储清除功能。
如果使用功能组件:

export const Component = () => {

const dispatch = useDispatch();

useEffect(() => {
  return () => {
    dispatch(yourActionThatCleansReduxStore())
  }
}, [])

//rest of your code
}

在我的例子中,我为每个页面URL(如/info/user)重置我的商店的一部分,商店看起来像

{
  user: {
   id: ...
  },
  info: ...
}
oo7oh9g9

oo7oh9g92#

可以使用子组件创建路径控制器

import { useDispatch } from "react-redux";
import { useLocation } from "react-router-dom";
import { cleanState } from "Your-reducer.js";    

function CleanState({ children }) {
  const location = useLocation();
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(cleanState()); // every time the route changes clean the state
    // if you don't use redux-toolkit you can use action.payload etc....
  },[location.pathname])

  return <>{children}</>;
}

export default CleanState;

你就得把主要的部分

import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import YourComponents from "./YourComponents"; // Your components
import CleanState from "./CleanState"; // where did you save it

function App() {
  return (
    <Router>
      <CleanState> // This is the previous component, this will listen the movements of the routes
         <Routes>
           <Route path="/main" element={<YourComponents />} />
           <Route path="*" element={<YourComponents />} />
         </Routes>
      </CleanState>
    </Router>
  );
}

export default App;

相关问题