javascript 如何使用getServerSideProps方法

qojgxg4l  于 2023-01-11  发布在  Java
关注(0)|答案(1)|浏览(112)

我试图使我的网页搜索引擎优化友好使用getServerSideProps方法。我曾试图谷歌它,但无法找到任何具体的例子,我的情况下。我不知道如何做到这一点。我有一个useEffect方法目前。

import Header from './Header.js';
import Footer from './Footer.js';
import React, { Component, useState, useEffect }  from 'react';
import Link from 'next/link';
import { useParallax, ParallaxBanner } from "react-scroll-parallax";
import { useTranslation } from "react-i18next";
import axios from "axios";
//import { Link, useLocation } from 'react-router-dom';

import Post from "./Post";

function Article({postSlug}) {

     const { t, i18n } = useTranslation();
     const [post, setPost] = useState([]);
     const [posts, setPosts] = useState([]);
     const currentlocale = typeof window !== 'undefined' ? localStorage.getItem('locale') : null;
     
     useEffect(() => {

        if(postSlug){
            axios({
            method: "POST",
            url: process.env.NEXT_PUBLIC_API_URL + '/pages/article',
            headers: { 'Content-Type': 'application/json;charset=UTF-8', "Access-Control-Allow-Origin": "*", "Accept": "application/json" },
            data: {
                country: currentlocale,
                slug: postSlug
            }
            }).then(result => {
                setPost(result.data.json.article);
                setPosts(result.data.json.articles);
                
            });
        }
          
     }, [postSlug])

    return (
        <div id="web-front">

            <Header />

            {post.title}

            <Footer />

        </div>
    )
}

export default Article;
oiopk7p5

oiopk7p51#

  • getServerSideProps仅在/pages文件夹内创建的路线/文件上运行。
  • 将数据获取方法从组件移到getServerSideProps函数。
  • 可以从getServerSideProps接收的context.req [1]对象中获取postSlug
  • LocalStorage在服务器上不可用。请使用cookies替换localStorage,因为cookiescontext.req对象上可用。[2]
function Article({ initialPost, initialPosts }) { //👈 received from ssr props
  const { t, i18n } = useTranslation();
  const [post, setPost] = useState(initialPost); // set initially
  const [posts, setPosts] = useState(initialPosts); // set initially

  return (
    <div id="web-front">
      <Header />

      {post.title}

      <Footer />
    </div>
  );
}

export async function getServerSideProps(ctx) {
  const postSlug = ctx.req.params.postSlug; // 👈 handled by you

  const currentLocale = getCurrentLocaleFromCookies(ctx.req); // 👈 handled by you

  let initialData = {};

  try {
    initialData = await axios({
      method: 'POST',
      url: process.env.NEXT_PUBLIC_API_URL + '/pages/article',
      headers: {
        'Content-Type': 'application/json;charset=UTF-8',
        'Access-Control-Allow-Origin': '*',
        Accept: 'application/json',
      },
      data: {
        country: currentlocale,
        slug: postSlug,
      },
    });
  } catch (err) {
    console.error(err);
  }

  return {
    props: {
      initialPost: initialData.data.json.article,
      initialPosts: initialData.data.json.articles,
    },
  };
}

export default Article;
参考:
  1. https://nextjs.org/docs/api-reference/data-fetching/get-server-side-props
  2. https://stackoverflow.com/a/63875689/7679903

相关问题