You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用React Router定位元素ID失败问题求助

Hey Jordan, let's break down why your anchor links aren't working and fix it step by step.

First: You're passing a custom history prop to BrowserRouter (which you shouldn't)

In React Router v4 and above, the BrowserRouter component does not accept a history prop — it creates its own internal history instance automatically. By passing your manually created history object, you're creating a mismatch between the history used by the router and the history used by your Link components. That's one major reason your anchor links aren't behaving as expected.

Fix your AppRouter by removing the history prop from BrowserRouter:

// You can probably remove the createHistory call entirely if you don't need it elsewhere
class AppRouter extends React.Component {
 render() {
 return (
 <BrowserRouter> {/* Removed the invalid history={history} prop */}
 <div>
 <Menu/>
 <Switch>
 <Route path="/" component={HomePage} exact={true} />
 <AdminRoute path="/admin" component={AdminPage} />
 <Route path="/plays" component={PlaysPage} />
 <Route path="/prose" component={ProsePage} />
 <Route path="/events" component={EventsPage} />
 <Route path="/content/:id" component={ContentDisplay} />
 <Route path="/create-account" component={CreateAccountPage} />
 <Route component={NotFoundPage} />
 </Switch>
 <Footer />
 </div>
 </BrowserRouter>
 );
 }
}
export default AppRouter;
// Remove the export { history } line if you no longer need it

Second: Fix the broken history.push in PlaysPage

Your componentDidMount has a problematic line that's causing invalid route navigation and interrupting anchor behavior:

history.push(`/${window.location.pathname}`)

window.location.pathname already starts with a /, so this creates a broken path like //plays. Delete this line entirely.

Third: Add anchor scroll handling (React Router doesn't do this by default)

React Router won't automatically scroll to elements when using hash anchors, especially not when your content loads asynchronously. We need to add explicit logic to scroll to the anchor after your content is fully rendered.

Update your PlaysPage with this scroll logic:

import { withRouter } from 'react-router-dom';

class PlaysPage extends React.Component{
 state = { plays: this.props.content };

 componentDidMount(){
 this.props.startSetContent()
 .then(() => {
 this.setState({ plays: this.props.content }, () => {
 // Wait for state to update and content to render before scrolling
 this.scrollToAnchor();
 });
 });
 }

 // Helper method to handle anchor scrolling
 scrollToAnchor() {
 const hash = window.location.hash;
 if (hash) {
 const targetElement = document.querySelector(hash);
 if (targetElement) {
 // Optional: Add smooth scroll behavior
 targetElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
 }
 }
 }

 // Handle anchor changes if the route updates while on this page
 componentDidUpdate(prevProps) {
 if (this.props.location.hash !== prevProps.location.hash) {
 this.scrollToAnchor();
 }
 }

 render () {
 return(
 <div className="plays">
 <div className="ten-min-plays">
 <h1 id="ten-minute-plays" className="ten-min-plays__title"> 10 Minute Plays </h1>
 {/* Rest of your page content */}
 </div>
 </div>
 )
 }
}

// Wrap the component with withRouter to access the location prop
export default withRouter(PlaysPage);

Why this works:

  1. We fixed the history mismatch that was breaking link behavior
  2. We removed the invalid route push that was interrupting the anchor flow
  3. We added scroll logic that runs only after your content loads and renders, ensuring the target element exists in the DOM
  4. We added componentDidUpdate to handle cases where the anchor changes while you're already on the PlaysPage

Give these changes a try — your anchor links should now scroll to the correct element as expected.

内容的提问来源于stack exchange,提问作者Jordan Hensley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:09:19