简体   繁体   English

我可以使用 getServerSideProps 中的服务器端属性在 NextJS 中初始化动态 state 吗?

[英]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.

相关问题 使用 NextJS 确保敏感代码仅在服务器端运行,这样的代码可以从哪里运行? - Ensuring sensitive code is run only server-side with NextJS, where can such code be ran from? 我可以使用服务器端Javascript在Razor中对视图进行编码吗? - Can I use server-side Javascript to code views in Razor? 我可以在服务器端标记内使用JavaScript变量吗? - Can I use a JavaScript variable within Server-Side Tags? GWT:如何使用服务器端排列选择? - GWT: How can I use Server-Side Permutation Selection? 我可以将 UseState 与服务器端渲染一起使用吗? Nextjs/JavaScript - Can I use UseState with Server-Side-Rendering? Nextjs/JavaScript Nextjs 中使用 getServerSideProps 进行动态路由 - Dynamic routing with getServerSideProps in Nextjs Nextjs getServerSideProps 未传递更新的道具 - Nextjs getServerSideProps not passing updated props 如何在 NextJs 中运行服务器端脚本? - How to run server-side scripts in NextJs? 为什么我不能在 NextJS 的 getServerSideProps 中记忆? - Why can't I memoize in NextJS' getServerSideProps? 我应该如何以可靠地用于转换为其他时区的方式在服务器端存储来自JS的时间戳? - How should I store a timestamp coming from JS on the server-side in a way that I can reliably use to convert to other timezones?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM