返回下一个js时如何更改滚动行为? [英] How to change scroll behavior while going back in next js?

查看:13
本文介绍了返回下一个js时如何更改滚动行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我像这样在索引 js 中获取帖子列表:

const Index = (props) =>{返回 (

{props.posts.map((每个) => {返回 (<链接滚动={false} as={`/post/${each.id}`} href="/post/[id]"key={each.id}><a><h1>{each.title}</h1></a></链接>);})}</div>);};导出异步函数 getStaticProps() {常量 url = `https://jsonplaceholder.typicode.com/posts`;const res = 等待 axios.get(url);返回 {道具:{帖子:res.data}};}

当用户点击任何链接时,它会转到发布页面:

函数 post({ post }) {返回 (<h1>{post.id}</h1>);}导出异步函数 getServerSideProps({ query }) {常量 { id } = 查询;const res = await Axios.get(`https://jsonplaceholder.typicode.com/posts/${id}`);返回 {道具:{帖子:res.data}};}

问题是当我单击返回时,滚动位置重置为顶部并获取所有帖子.我在 Link 中包含 scroll={false} 但它不起作用.

当用户从帖子页面点击返回时,如何防止滚动重置?

解决方案

Next.js 实际上已经内置支持返回上一页时恢复滚动位置.我们可以简单地通过编辑 next.config.js 来启用它:

module.exports = {实验:{滚动恢复:真,},}

I fetch a list of posts in index js like this :

const Index = (props) => {
    return (
        <div>
            {props.posts.map((each) => {
                return (
                    <Link scroll={false} as={`/post/${each.id}`} href="/post/[id]" key={each.id}>
                        <a>
                            <h1>{each.title}</h1>
                        </a>
                    </Link>
                );
            })}
        </div>
    );
};

export async function getStaticProps() {
    const url = `https://jsonplaceholder.typicode.com/posts`;
    const res = await axios.get(url);

    return {
        props: { posts: res.data }
    };
}

And when user clicks on any link it goes to post page which is :

function post({ post }) {
    return (
            <h1>{post.id}</h1>
    );
}

export async function getServerSideProps({ query }) {
    const { id } = query;
    const res = await Axios.get(`https://jsonplaceholder.typicode.com/posts/${id}`);

    return {
        props: { post: res.data}
    };
}

The problem is when I click back the scroll position resets to top and it fetches all posts . I included scroll={false} in Link but it doesn't work .

How can I prevent scroll resetting when user clicks back from the post page ?

解决方案

Next.js in fact has built-in support for restoring scroll position when back to the previous page. We can simply enable it by editing the next.config.js:

module.exports = {
  experimental: {
    scrollRestoration: true,
  },
}

这篇关于返回下一个js时如何更改滚动行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆