导航到React中的另一个页面时,我试图在onClick时保存布尔值。
按下IconButton时,用户导航到/ app / new,并且bookRide对象被字符串化并保存为状态: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中。
答案 0 :(得分:0)
链接的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>
)}
}