reactjs - 在 React 中导航到另一个页面时在会话存储中设置项目
问题描述
当导航到 React 中的另一个页面时,我试图在 onClick 时保存一个 bool true 。
当 IconButton 被按下时,用户导航到 /app/new 并且 bookRide 对象被字符串化并以 status: true 保存。当用户导航回 BookRide 组件时,此状态仍然为 true。
class BookRide extends Component {
constructor(props) {
super(props);
let bookRide= JSON.parse(sessionStorage.getItem('bookRide'));
this.state = {
bookRide: bookRide? bookRide: { status: false },
}
this.handleBookRide= this.handleBookRide.bind(this);
}
handleBookRide= () => {
this.setState(() => ({
bookRide: {
...this.state.bookRide,
status: true,
}
}), function callback() {
const { bookRide} = this.state;
sessionStorage.setItem('bookRide', JSON.stringify(bookRide));
})
}
render() {
return (
<IconButton
component={Link}
to={{
pathname: `/app/new`,
}}
onClick={this.handleBookRide}
</IconButton>
)}
}
目前,bookRide 对象根本没有保存在 sessionStorage 中。
解决方案
链接的 IconButton 功能导致了问题。重写了这个:
class BookRide extends Component {
constructor(props) {
super(props);
let bookRide= JSON.parse(sessionStorage.getItem('bookRide'));
this.state = {
bookRide: bookRide? bookRide: { status: false },
}
this.handleBookRide= this.handleBookRide.bind(this);
}
handleBookRide= () => {
this.setState(() => ({
bookRide: {
...this.state.bookRide,
status: true,
}
}), function callback() {
const { bookRide} = this.state;
sessionStorage.setItem('bookRide', JSON.stringify(bookRide));
this.props.history.push (`/app/riders/new`);
})
}
render() {
return (
<IconButton
onClick={this.handleBookRide}
</IconButton>
)}
}
推荐阅读
- node.js - 无法使用 node.js 执行脚本外壳
- fortran - 在fortran95中读取和写入文件
- powershell - Get-ChildItem 为 Assembly.*.dll 添加排除过滤器但包括 Assembly.Some.*.dll
- emacs - 当 emacs *scratch* 缓冲区打开时自动粘贴剪贴板内容
- json - 如何在一个命令中从对象的差异字段中提取一些值
- asp.net - 使用客户端应用程序测试 Aspnet.security.openidconnect.server
- python - 如何使用 Selenium (Python) 在网页中找到“警报警告”
- c# - 将 UIScrollview 中显示的图像裁剪为覆盖层中显示的矩形
- sql - 如何按 X 天过滤 SQL 查询日期结果
- python - 删除与大小相关的单词,而不是其他列表中的单词