[英]Can I use server-side props from getServerSideProps to initialize dynamic state in NextJS?
I'm currently creating a simple application using NextJS and I'm wondering what the best way is to handle SSR using data from an API that will also be dynamic on the page.我目前正在使用 NextJS 创建一个简单的应用程序,我想知道使用 API 中的数据处理 SSR 的最佳方法是什么,该数据在页面上也是动态的。 My current approach is outlined as follows, and I'm curious as to whether this is how it should be done in NextJS.我目前的方法概述如下,我很好奇这是否应该在 NextJS 中完成。
I retrieve a set of todos from the free JSON Placeholder API using getServerSideProps
inside of my Home
page component as follows (please note that I'm using TypeScript):我使用Home
组件内的getServerSideProps
从免费的 JSON 占位符 API 中检索了一组待办事项,如下所示(请注意我使用的是 TypeScript):
export const getServerSideProps: GetServerSideProps = async () => {
const todoAPIResponse = await fetch('https://jsonplaceholder.typicode.com/todos?_limit=10');
const todos = await todoAPIResponse.json();
return {
props: {
todos,
},
};
};
The Home
component is defined as: Home
组件定义为:
const Home: NextPage = ({ todos }: HomeProps) => {
const [todoState, setTodoState] = useState(todos);
const [newTodo, setNewTodo] = useState('');
const onSubmit = (event: any) => {
event.preventDefault();
setTodoState((prev: any) => [...prev, { title: newTodo }]);
setNewTodo('');
};
return (
<div className={styles.container}>
{todoState.map((todo: any) => <p key={todo.id}>{todo.title}</p>)}
<form onSubmit={onSubmit}>
<input value={newTodo} onChange={(event) => setNewTodo(event.target.value)} />
</form>
</div>
);
};
As you can see inside of the Home
component, I am initializing todoState
using the props (the data retrieved from the API), and then the data becomes dynamic with the ability to create new todos with the form.正如您在Home
组件内部看到的那样,我正在使用 props(从 API 检索的数据)初始化todoState
,然后数据变成动态的,能够使用表单创建新的待办事项。 In the typical "React way", I understand that the todos would be initialized as an empty array, then inside of a useEffect
, the API could be called and then the state could be set from there, however, I'm trying to understand what the proper way of doing this in NextJS is as I am new to the framework and the concept of SSR.在典型的“反应方式”中,我知道 todos 将被初始化为一个空数组,然后在useEffect
内部,可以调用 API 然后可以从那里设置 state,但是,我试图理解在 NextJS 中执行此操作的正确方法是什么,因为我是框架和 SSR 概念的新手。
I believe you are doing it right.我相信你做对了。
The approach between ssr and react is different. ssr 和 react 之间的方法是不同的。 In the ssr version, you need a server first, so that each call to this page would make this fetch
before a HTML page is assembled and sent back to the UI .在 ssr 版本中,您首先需要一个服务器,以便每次调用此页面都会在 HTML 页面组装并发送回UI之前进行此fetch
。 And afterwards, the NextJS will hydrate this page to make it like a regular React page by attaching all the other dynamic attributes.之后, NextJS将通过附加所有其他动态属性来水化该页面,使其像普通的React页面一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.