首页 > 解决方案 > 在 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 中。

标签: reactjs

解决方案


链接的 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>
)}

}

推荐阅读