[英]How to make Next.js do SSR (Server Side Rendering)?
To experiment with Next.js, I created an empty Next.js project, and added some code to fetch data for weather:为了试验 Next.js,我创建了一个空的 Next.js 项目,并添加了一些代码来获取天气数据:
export default function Home() {
const [data, setData] = useState(null);
useEffect(() => {
fetch("https://api.weather.gov/gridpoints/MTR/84,105/forecast")
.then((res) => res.json())
.then((d) => setData(d));
}, []);
const details = data && data.properties.periods[0];
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
Hello world
{details && (
<div>
<h2>San Francisco Forecast</h2>
<img src={details.icon} />
<p>
Temperature: {details.temperature}°{details.temperatureUnit} /{" "}
{Math.round(((details.temperature - 32) * 50) / 9) / 10}°C
</p>
<p>{details.shortForecast}</p>
<p>{details.detailedForecast}</p>
<p>{new Date(details.startTime).toLocaleString()}</p>
</div>
)}
</main>
</div>
)
}
Demo: https://codesandbox.io/s/staging-snow-6tvqc?file=/pages/index.js演示: https://codesandbox.io/s/staging-snow-6tvqc?file=/pages/index.js
and the standalone page: https://6tvqc.sse.codesandbox.io/和独立页面: https://6tvqc.sse.codesandbox.io/
How can we make the following command我们如何制作以下命令
curl https://6tvqc.sse.codesandbox.io/
be able to show the content as if on the webpage?能够像在网页上一样显示内容吗? (so should be able to have
Temperature
and the numbers after it). (所以应该能够有
Temperature
和它后面的数字)。
Do data fetching in these functions.在这些函数中获取数据。
Next.js provides 3 functions for data fetching. Next.js 提供 3 种数据获取功能。 You have to export them from your page.
您必须从您的页面导出它们。
You have to return data in a format and it will be injected in props of your react component.您必须以某种格式返回数据,它将被注入到您的 react 组件的 props 中。
You can also provide fallback on props to dynamically render pages, like you don't have to make every page static (using GetStaticProps/Paths).您还可以在道具上提供后备以动态呈现页面,就像您不必制作每个页面 static(使用 GetStaticProps/Paths)一样。 Make only some of them and Next.js will make remaining on request and will cache them for next request.
只制作其中的一些,Next.js 将在请求时剩余,并将缓存它们以供下一个请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.