我在我的webapp中有react-redux和react-router,而我试图在保持redux状态的同时更改路由。我尝试了所有这些,它们都删除了redux状态:
props.history.push({ pathname: `/my-path`}); // did this using withRouter and useHistory
<Link to={'/my-path'} />cool link</Link>我做错了什么?我怎样才能保持状态?(我不能将其保留在localStorage中的原因是,当用户关闭该页面时,数据应该会消失)
发布于 2020-11-17 04:38:35
Redux不会在你刷新网站后保留状态。如果希望持久化数据,则应使用localStorage,并在关闭浏览器或页面后使用event window.onunload清除数据。
查看此gist
或者,您也可以在以编程方式导航时传递数据,如下所示
import { useHistory } from 'react-router-dom'
...
function myComponentA() {
const history = useHistory()
const navigate = () => {
history.push('/pageB', {
id: 7,
name: 'Dan'
color: 'Red'
})
}
return <button onClick={navigate}>Go to page B</button>
}
...在组件B中,使用钩子useLocation(),然后访问状态属性,您应该会在那里看到您的数据。
import { useHistory } from 'react-router-dom'
...
function myComponentB() {
const location = useLocation()
return <h1>{location.state.name}</h1>
}
...引起我注意的是,如果您使用的是react-router-dom,链接按钮应该在redux存储中保留状态。只有在您的浏览器重新加载后,才会清除数据。使用钩子和redux-toolkit检查this sample,这可能是您问题的真正解决方案。一旦导航到组件B,状态就应该保持不变。
有关更多文档,请参阅
Redux工具包:https://redux-toolkit.js.org/ react-router-dom:https://reactrouter.com/web/guides/quick-start
https://stackoverflow.com/questions/64864720
复制相似问题