我有一个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
}
});
答案 0 :(得分:4)
我发现你可以将组件的方法附加到监听器:
componentDidMount() {
window.addEventListener("popstate", this.setSongFromHistory);
}
setSongFromHistory(e) {
if(e.state.song){
e.preventDefault(); // stop request to server for new html
e.stopPropagation();
this.setState({song: e.state.song});
$('html,body').scrollTop(0);
}
}