【发布时间】:2017-10-05 22:12:42
【问题描述】:
我有这段代码:
class Base extends Component {
changeRoute = () => {
// after this, address bar gets updated but I can't see the Users
// component, only Home component.
this.props.history.push('/users');
}
render() {
return (
<div>
<MyBar />
{this.props.children}
</div>
)
}
}
class App extends Component {
render() {
return (
<Router>
<Base>
<a onClick={this.changeRoute}>Change</a>
<Route path="/home" component={Home} />
<Route path="/users" component={Users} />
</Base>
</Router>
)
}
}
但是,当我尝试使用 history.push 或从 react-router-redux 推送来更改位置时,我可以看到浏览器路径已更新但内容未更新,它显示了原始路径内容。我还注意到,每当我刷新浏览器时,我都能看到与路径相关的正确内容。
当我将代码更改为以下内容时,浏览器路径和内容都会按预期相应更新,我的问题是:为什么它的行为不同?如果在我看来这两个代码都做同样的事情。
class Base extends Component {
render() {
return (
<MyBar />
)
}
}
class App extends Component {
changeRoute = () => {
// after this, address bar and component are updated as expected.
this.props.history.push('/users');
}
render() {
return (
<Router>
<div>
<Base />
<a onClick={this.changeRoute}>Change</a>
<Route path="/home" component={Home} />
<Route path="/users" component={Users} />
</div>
</Router>
)
}
}
编辑: 我在源代码中添加了 push 方法。这是我用来导出 App 组件的一段代码:
import {withRouter} from 'react-router';
export default withRouter(App);
【问题讨论】:
-
使用
withRouter的 react-router-dom 像withRouter(App)
标签: reactjs react-router