我正在尝试使用react-router历史记录的侦听器来触发某些事件。为此,我已经在componentDidMount
函数中注册了侦听器。在测试中,我向历史记录推送了一些路径,因此我假设侦听器将被触发,但是push事件不会触发侦听处理程序。
组件类
class MyComponent extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
console.log('Current Location: ' + JSON.stringify(this.props.history.location));
//Print this OK: {"pathname":"/","search":"","hash":"#home","state":null,"key":"ae0ezb1m"}
this.props.history.listen(() => {
//Never gets here
if(this.props.location.hash && this.props.location.hash.includes('home')) {
//Also does not gets here
console.log('Welcome Home!!!');
}
});
}
}
测试
it('should print Welcome Home', () => {
const fakeHistory = createMemoryHistory({
initialEntries: ['/#home'],
initialIndex: 0
});
shallow(<MyComponent />);
});
有什么建议吗?