在我的代码中,当我单击按钮时,不会重新渲染组件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>
}
答案 0 :(得分:2)
正确的方法是在尝试手动导航(通过单击按钮)时使用<Link to='/about'>to About</Link>
,在尝试自动导航(例如完成API调用之后)时使用window.history.pushState('','','/about')
。
答案 1 :(得分:2)
由于window.history.pushState未使用React路由器 因此您可以使用链接在页面之间导航。 但是如果您有限制并且希望它成为一个对接并且仍然使用react router进行导航,则可以使用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