【发布时间】:2022-01-21 23:00:15
【问题描述】:
我通过在 react 中使用 useState 钩子来维护状态。我想清除在路由更改时保持状态的值。
例如 - 我在基于反应的项目中声明了 4 条路线。如下
<Router>
<Layout>
<Route exact path="/" component={Home}></Route>
<Route exact path="/defineFacilities" component={DefineFacilities}></Route>
**<Route exact path="/createNewModel/:id" component={ModelFormsContainer}></Route>**
<Route exact path="/viewExistingModels" component={ViewExistingModels}></Route>
<Route exact path="/importNewModel" component={ImportNewModel}></Route>
</Layout>
我在 ModelFormsContainer 组件中维护了状态。当用户移动到其他路线时,我想清理状态值。目前,当我移动到其他路线并返回 ModelFormsContainer 组件时,我注意到我的状态仍然可用。
【问题讨论】:
-
在您决定移动到另一个页面后立即将其设置为空字符串或 null
-
使用 useEffect hook 中的清理功能。它在组件卸载时调用。在此函数中,您可以将状态设置为 null。顺便说一句,卸载组件时反应会破坏状态。
-
@MhkAsif 是的,当第一次为新表单设置状态时 useEffect 正在工作,但是当同一组件处于编辑模式时(意味着根据将数据保存到数据库中填充状态)以及尝试更改时会失败路由并返回组件然后我的状态没有变干净。 const [formState, setFormState] = useState
(defaultValueFormState); useEffect(()=>{ console.log('useEffect') return ()=>{ setFormState(defaultValueFormState); } },[]) -
本地组件状态被转储并且
ModelFormsContainer在改变路由时被卸载。这里似乎还有其他事情发生。您可以将所有相关代码添加到您的问题中吗?你能分享ModelFormsContainer组件以及它在安装时的作用,以及当路由发生变化时。编辑模式在做什么? -
我同意@DrewReese ,组件未卸载似乎很奇怪。也许尝试使用
children而不是component道具:<Route exact path="/createNewModel/:id"><ModelFormsContainer /></Route>。该道具上的文档对我来说有点不清楚。 v5.reactrouter.com/web/api/Route/component
标签: reactjs react-hooks react-router