我有一个使用 create-react-app 创建的 react 应用程序,并且正在使用 react-router-dom 进行路由。
总体布局为:
应用程序.js
<BrowserRouter>
<BodyContent />
</BrowserRouter>
正文内容.js
<Fragment>
<Navigation/>
<main>
<ScrollToTopRoute path="/" exact component={HomePage}/>
<ScrollToTopRoute path="/page1" exact component={Page1}/>
<ScrollToTopRoute path="/page1/page2" exact component={Page2}/>
<ScrollToTopRoute path="/page3" exact component={Page3}/>
... etc...
</main>
</Fragment>
ScrollToTopRoute 只是标准路由器功能的扩展,可确保新页面滚动回顶部以获得良好的用户体验。
滚动到顶部.js
import React, { Component } from 'react';
import { Route, withRouter } from 'react-router-dom';
import ReactGA from 'react-ga';
ReactGA.initialize('UA-5477132-2');
class ScrollToTopRoute extends Component {
componentDidUpdate(prevProps) {
if (this.props.path === this.props.location.pathname && this.props.location.pathname !== prevProps.location.pathname) {
window.scrollTo(0, 0);
ReactGA.pageview(window.location.pathname + window.location.search);
console.log("Triggered");
}
}
render() {
const { component: Component, ...rest } = this.props;
return <Route {...rest} render={props => (<Component {...props} />)} />;
}
}
export default withRouter(ScrollToTopRoute);
在开发过程中,应用程序按预期工作,所有路由都可以正常工作,如果您直接转到类似的 URL localhost:3000/page1
,它将正确加载。我已经使用 yarn build 构建了站点并部署到典型的 VPS。网站和组件/路由的内部链接都按预期工作,但是当直接访问 URL 时,例如www.theurl.com/page1
404,我不知道为什么结果不同。