Javascript 更改页面或重新加载页面时,请滚动至react中的锚定标记
我正在尝试滚动到页面上的锚定标记,内容是通过使用axios的API填充的。我的问题是页面在重新加载/页面更改时没有滚动到正确的点。我不确定我错过了什么/做错了什么 在react路由器上,我将窗口滚动到页面顶部,因为我希望用户从页面顶部开始:Javascript 更改页面或重新加载页面时,请滚动至react中的锚定标记,javascript,reactjs,scroll,react-router,anchor,Javascript,Reactjs,Scroll,React Router,Anchor,我正在尝试滚动到页面上的锚定标记,内容是通过使用axios的API填充的。我的问题是页面在重新加载/页面更改时没有滚动到正确的点。我不确定我错过了什么/做错了什么 在react路由器上,我将窗口滚动到页面顶部,因为我希望用户从页面顶部开始: ReactDOM.render( <Router history={browserHistory}> <Route path="/" onChange={(prevState, nextState
ReactDOM.render(
<Router history={browserHistory}>
<Route
path="/"
onChange={(prevState, nextState) => {
if (nextState.location.action !== 'POP') {
window.scrollTo(0, 0);
}
}}
component={App}
>
<IndexRoute pageId={5} background="" component={Home}/>
<Route path="/your-journey" pageId={7} component={YourJourney}/>
<Route path="/designed-for-you" pageId={6} component={DesignedForYou}/>
<Route path="/your-gateway" background="" pageId={1} component={YourGateway}/>
<Route path="/get-in-touch" background="no-hero-image" pageId={4} component={GetInTouch}/>
<Route path="/legal-and-compliance" background="no-hero-image" pageId={8} component={Legal}/>
<Route path="/privacy" background="no-hero-image" pageId={9} component={Privacy}/>
</Route>
</Router>,
document.getElementById('root')
);
已加载数据的状态的设置如下所示:
constructor(props) {
super(props);
this.state = {
pageId: '',
dataLoaded: false,
data: {
title: '',
body: '',
image: '',
imageRows: [],
footer: []
}
};
}
然后在componentDidMount函数中设置:
if (window.location.hash && this.state.dataLoaded) {
console.log(this.state.dataLoaded);
let offset = 0;
if (window.innerWidth > 768) {
offset = 174;
} else {
offset = 150;
}
setTimeout(() => {
scrollToElement(window.location.hash, {
offset: -offset,
ease: 'outSine',
duration: 1500
});
}, 0);
}
componentDidMount() {
this.serverRequest = axios.get(config.API_BASE + config.GALLERY_API + '/' + this.state.pageId).then(response => {
if (this.unmounted) {
return;
}
const res = response.data;
if (response.status === 200) {
this.setState({
data: res,
dataLoaded: true
});
}
});
}
是否有人想出了一个好的解决方案?我不能使用scrollintoview功能,因为没有任何设置
更多信息是我正在使用标签来更改页面
谢谢
编辑:
我已将scroll函数移动到promise/200响应if中的componentDidMount函数。我还将设置的超时时间更改为250ms,这解决了我的重新加载问题,并转到了正确的位置。我认为/知道这是一个黑客行为,所以请告诉我如何以更好的方式解决这个问题