我正在使用React [15.6.1]和Router [4.1.1]构建文章搜索,并注意到当尝试直接访问文章时,前一个组件被加载,即使你不是被调用的那个< / p>
// === Layout ==================
class Layout extends React.Component {
render() {
return (
<Provider store={this.props.store}>
<HashRouter>
<div>
<Switch>
<Route exact path="/" component={SearchFilter} />
<Route path="/article/:guid" component={Article} />
</Switch>
</div>
</HashRouter>
</Provider>
);
}
}
// === SearchFilter ==================
class SearchFilter extends React.Component {
componentDidMount() {
console.log('SearchFilter Did Mount');
}
render() {
return (
<div>...</div>
);
}
}
// === Article ==================
class Article extends React.Component {
componentDidMount() {
console.log('Article Did Mount');
}
render() {
return (
<div>...</div>
);
}
}
因此,当进入根 localhost:3000 /#/ 时,会打印
// SearchFilter Did Mount
当我直接访问一篇文章 localhost:3000 /#/ article / 123456 时,会打印
// SearchFilter Did Mount
// Article Did Mount
所以我的问题是,如何阻止它运行上一条路线? 因为我想在那里调度一些会触发对web服务的ajax调用。
由于
答案 0 :(得分:0)
请改为尝试:
<HashRouter basename="/">
<div>
<Switch>
<Route exact path="/search" component={SearchFilter} />
<Route path="/article/:guid" component={Article} />
</Switch>
</div>
</HashRouter>
答案 1 :(得分:0)