我有一个React组件,当状态发生改变时会将歌曲ID推送到URL。我的问题是:当用户在浏览器上点击“后退”按钮时,我需要更改SongApp组件的状态。我该如何做?
class SongApp extends React.Component {
constructor(props) {
super(props);
this.state = {
song: props.songId
}
this.setSong = this.setSong.bind(this);
}
setSong(e) {
var songId = e.target.id;
this.setState({song: songId})
window.history.pushState({song: songId}, '', '?s='+songId)
}
render() {
var id = this.state.song;
var content = id ? <SongDisplay lyrics={ this.props.songData[id].lyrics } /> : <SongIndex songData={this.props.songData} setSong={this.setSong}/>
return(
<div className="song-app">
{content}
</div>
)
}
}
window.addEventListener('popstate', function(event) {
console.log('popstate fired!');
debugger;
if(event.state.song) {
// change SongApp state
}
});
this
没有正确设置。解决方法是执行window.addEventListener("popstate",(e) => this.setSongFromHistory(e))
。 - Garr Godfrey