反应路由器包含
withRouter
higher-order component
可以为应用程序提供相关的道具栏组件。
history.js
history.goBack()
,它无法单独在应用程序上导航,因为窗口历史记录可能包含其他网站。
组件可以如下所示(a
demo
)并且应该是路由器组件的子级以获取路由器道具:
@withRouter
class AppBar extends Component {
state = {
locations: [this.props.location]
};
componentDidMount() {
this.props.history.listen((location, action) => {
if (action === 'REPLACE')
return;
this.setState({
locations: [location, ...this.state.locations]
})
});
}
back = () => {
const [location, ...locations] = this.state.locations;
this.setState({ locations });
this.props.history.replace(location);
}
render() {
return (
<>
{this.state.locations.length > 1 && <button onClick={this.back}>Back</button>}
</>
);
}
}
它跟踪位置的变化并在其中导航。将其与浏览器历史记录导航按钮(后退和前进)保持同步将是一项更为复杂的任务。