我在像“/dashboard”这样的路径上有一个 Dashboard.js 页面组件,它允许用户通过更改其状态而在 3 个表之间导航,同时 URL 保持不变(路由不变)。我正在尝试为这些状态更改添加浏览器后退/前进按钮支持,但我一直在尝试弄清楚如何将状态更改推送到历史记录并在用户单击后退/前进按钮时在组件中恢复它们。
在我的组件中,我尝试添加this.props.history.push(this.props.location.path, this.state)
到我的主要功能之一,setState()
看看是否允许后退按钮导航。它肯定会增加历史记录,因为现在我可以在离开页面之前按后退按钮几次,但页面看起来相同(组件不会恢复旧状态)。当按下后退按钮时,如何以及在哪里使组件“恢复旧状态”?
这是我的组件结构的基本示例:
class Dashboard extends Component {
state = {
// table data, current table, etc.
}
componentDidMount() {
// get records from db, set state
}
navigateExample() {
// various functions like this one set state,
// basically navigating between tables
this.props.history.push(this.props.location.path, this.state) // <--here?
this.setState({ table: newTable })
}
render() {
// renders different table components depending on state
}
}
Run Code Online (Sandbox Code Playgroud)
如果示例代码太模糊,我很抱歉,我的组件文件很大并且我不知道要包含哪些相关内容。先谢谢您的帮助。