gpt4 book ai didi

javascript - 在 react 服务器端渲染的应用程序中启用滚动

转载 作者:行者123 更新时间:2023-12-02 22:07:48 24 4
gpt4 key购买 nike

您好,我正在将 React 应用程序从客户端渲染(CSR)迁移到服务器端渲染(SSR)。我在 csr 中实现了下面的代码,以便在滚动到页面末尾时加载更多内容。我遇到的问题是,在将代码迁移到 ssr 后,它现在给出一个错误“ReferenceError:窗口未定义”。我如何重构代码,以便滚动位置在 react 服务器端渲染的应用程序中工作?

在 csr 中实现的代码,可实现滚动

export class AllCourses extends React.PureComponent {
constructor(props) {
super(props);

this.state = {

};
this.handleScroll();
}

.....

handleScroll() {
window.onscroll = () => {

const nextPage = this.props.nextPage;
if (
window.innerHeight + document.documentElement.scrollTop ===
document.documentElement.offsetHeight
) {
this.props.dispatch(retrieveAllCourses(nextPage));
}
};
}

最佳答案

您可以将 handleScroll 函数中的逻辑移至 useEffect 回调中,因为当组件呈现时,window 变量可用。

所以你会这样做:

componentDidMount() {
if (typeof window !== 'undefined') {
window.onscroll = () => {

const nextPage = this.props.nextPage;
if (
window.innerHeight + document.documentElement.scrollTop ===
document.documentElement.offsetHeight
) {
this.props.dispatch(retrieveAllCourses(nextPage));
}
};
}
}

关于javascript - 在 react 服务器端渲染的应用程序中启用滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59662030/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com