【问题标题】:NextJS production serverside rendering state not updatingNext JS 生产服务器端渲染状态未更新
【发布时间】:2021-11-02 12:19:28
【问题描述】:

所以在 NextJS 生产中,我的服务器端渲染和重新验证设置为 1s 的 React 项目不会随着页面的刷新而更新状态,所以基本上我在服务器端渲染一个页面,然后我还需要获取 API 来获取数据库中的最新值导致我的网站首先显示旧值然后闪烁到新值,这很烦人...... 有谁知道如何在代码中解决这个问题?

这是获取静态道具:

  export async function getStaticProps() {
      const response = await fetch(`link`);
      const data = await response.json();
    
      return {
        props: {
          data: data,
        },
        revalidate: 1,
      };
    }

这是页面加载时的 useEffect:

 useEffect(() => {
        fetchNewData(); //function to fetch an API
        if (error === null) setLoading(false);
      }, []);
      if (loading) return "Loading...";
      if (error) return "Error!";

【问题讨论】:

  • "revalidation set to 1s is not updates state with the refresh of the page" - 在@987654323之后的第一个请求中,页面内容不会更新@期间已经过去,那只会触发再生。然后以下请求将获取更新的页面。

标签: reactjs next.js


【解决方案1】:

尝试使用useSWR钩子而不是useEffect

npm i swr

代码:

 import useSWR from 'swr'
    
    function Profile() {
      //your API path
      const { data, error } = useSWR('/api/user', fetcher)
    
      if (error) return <div>failed to load</div>
      if (!data) return <div>loading...</div>
      return <div>hello {data.name}!</div>
    }

【讨论】:

    猜你喜欢
    • 2021-11-20
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 2012-01-17
    • 2019-04-07
    • 2021-10-30
    • 1970-01-01
    • 2021-06-20
    相关资源
    最近更新 更多