我想在路由中打开一个 popin,我想向 url 添加一个散列。
例如在 onClick https://www.example.com/home
之后 onClick https://www.example.com/home#send-me-an-email
很好,但是 React Router 会重新渲染整个路由。
我是不是对 React Router 做错了什么?让我们看看下面的代码(我简化了一些事情)
index.jsx
我像大家一样使用 BrowserRouter
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import App from './App';
const render = Component => {
ReactDOM.render(
<Router>
<Component />
</Router>,
document.getElementById('root')
);
};
render(App);
App.jsx
我正在使用 withRouter 因为我需要其他地方的历史和位置
import React from 'react';
import { Route, Switch, withRouter } from 'react-router-dom';
import Header from './components/Header';
import Footer from './components/Footer';
import Home from './views/Home';
const App = ({ ...props }) => {
return (
<Header />
<section>
<Switch>
<Route exact path={"/"} component={() => <Home {...props} />} />
<Route path={"/home"} component={() => <Home {...props} />} />
</Switch>
</section>
<Footer />
);
};
export default withRouter(App);
Home.jsx
不幸的是,当我执行 this.props.history.push({ hash: 'send-me-an-email' })
时,它会重新渲染路由组件 Home,不好
...
render() {
<div>
<button onClick={() => this.props.history.push({ hash: 'send-me-an-email' })}>
Send me and email
</button>
<Popin
isOpened={this.state.isPopinOpened}
handleClose={() => this.props.history.push({ hash: '' })} />
</div>
}
...
如何不因为我向相同的 url 添加了哈希而重新呈现?干杯。
最佳答案
简单地依赖 vanilla JS:
window.history.pushState("object or string", "Title", "/home#send-me-an-email");
这将添加一个散列/路由而不渲染或重新加载任何东西。
关于javascript - 如何在不重新渲染的情况下使用 React Router 将哈希添加到 url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57327432/