两次跳转同一个路由组件页面不刷新
时间: 2023-08-08 18:04:53 浏览: 160
在 React Router 中,当你跳转到同一个路由时,默认情况下并不会触发组件的重新渲染。这是因为 React Router 对于同一个路由的切换只会改变 URL,而不会重新加载组件。如果你想要在同一个路由下刷新组件,可以考虑以下两种方法:
- 使用
forceUpdate
方法强制刷新组件
你可以在组件中使用 forceUpdate
方法来强制刷新组件。这个方法会触发组件的 render
方法重新渲染,但并不会重新调用 componentDidMount
等生命周期方法。具体代码如下:
class MyComponent extends React.Component {
handleClick = () => {
this.forceUpdate();
}
render() {
return (
<div>
<button onClick={this.handleClick}>刷新</button>
<p>组件内容</p>
</div>
);
}
}
- 使用
key
属性改变组件的标识
另一种方法是在同一个路由下改变组件的标识,从而触发组件的重新渲染。你可以在 Route
组件上使用 key
属性来改变组件的标识。具体代码如下:
class MyComponent extends React.Component {
handleClick = () => {
this.props.history.push('/path/to/same/component', { key: Date.now() });
}
render() {
return (
<div>
<button onClick={this.handleClick}>刷新</button>
<p>组件内容</p>
</div>
);
}
}
<Route path="/path/to/same/component" render={(props) => <MyComponent key={props.location.state.key} {...props} />} />
在点击按钮时,我们通过 history.push
方法改变了路由,并传入一个随机的 key
值。在 Route
组件上,我们使用 render
属性来渲染组件,并根据 props.location.state.key
的值来改变组件的标识。这样,每次路由改变时,组件的标识都会发生变化,从而触发组件的重新渲染。
相关推荐


















