在 react-router 中使用 Link 组件和手动调用 'window.history.pushState()'



在我的代码中,当我单击按钮时,组件Aaaaa不会重新渲染,但是当我点击链接时,组件Aaaaa会重新渲染。 我找不到原因?

function App() {
return (
<>
<button onClick={() => window.history.pushState('','','/about')}>About</button>
<Link to='/about'>to About</Link>
<Aaaaaa/>
</>
);
}

和:

Aaaaaa(){
const location = useLocation()
return <div>About </div>
}

正确的方法是在尝试手动导航(通过单击按钮(时使用<Link to='/about'>to About</Link>,在尝试自动导航时使用window.history.pushState('','','/about')(例如在完成 API 调用后(。

导致 window.history.pushState 未使用 react 路由器 因此,您可以使用链接在页面之间导航。 但是如果你有限制,并且希望它是一个对接并且仍然使用 React 路由器导航,你可以使用 React-router-dom 的历史记录

import { withRouter } from 'react-router-dom'
// some other codes
const { history } = props;
// some other codes
<button onClick={() => history.push('/about')}>About</button>
// some other codes
export default withRouter(MyComponent)

或者,如果您使用的是 react-router v5,则可以使用 'useHistory' 钩子。

import { useHistory } from 'react-router-dom'
// some other codes
const history = useHistory();
// some other codes
<button onClick={() => history.push('/about')}>About</button>
// some other codes
export default MyComponent

我发现window.history.pushState('','','/about')无法按预期工作。路由器不会更新要显示的路由。

如果您不能使用按钮并且需要以编程方式控制位置,但使用类组件将其包装在函数组件中,如下所示:

... other routes
<Route exact path="/register" component={()=>{
const history = useHistory();
return <RegisterPage onRegister={async (account) => {
this.setState({ account });
history.push('/'); // sends user automatically to main page
}} />
}} />
...

window.history.pushState 方法不会触发任何浏览器事件,这反过来又不会通知 react 路由器您对 history 对象所做的更新

React 路由器自定义链接组件很可能会使用自定义事件或观察者设计模式来通知和响应窗口历史记录对象中的更改

最新更新