React – 每次重新访问页面时是否从服务器获取数据是一个好的实践?

huangapple go评论56阅读模式
英文:

React - Is it fetching from server every time that I revisit the page a good practice?

问题

在一个useEffect中进行数据获取是否是一个良好的实践,还是一个初学者的错误,我在某种程度上理解,当URL发生变化时,状态会被卸载,所以在这个示例中,变量data应该是一个新的空变量(被设置为null),是吗?

(以下代码是我示例中的一个骨架示例,供本文的问题参考)。

import React, { useState, useEffect } from 'react';

function MyComponent() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    const response = await fetch('https://myserver.com/data');
    const json = await response.json();
    setData(json);
  };

  return (
    <div>
      {data ? (
        <ul>
          {data.map((item) => (
            <li key={item.id}>{item.name}</li>
          ))}
        </ul>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
}

我应该尝试在本地存储所有数据吗?还是经常向服务器发起请求是正常的?在这里是否应该涉及React.memo

以下是翻译的内容,代码部分不翻译。

英文:

I'm wondering if making a fetch on a useEffect is a good practice or it is actually a beginner's mistake. As far as I understand, the state dismounts when the url is changed, so in the example, the variable data should be anew empty (set to null) variable, is that right?

(Below code being an skeleton example of mine, for this post's questions purposes).

import React, { useState, useEffect } from &#39;react&#39;;
    
    function MyComponent() {
      const [data, setData] = useState(null);
    
      useEffect(() =&gt; {
        fetchData();
      }, []);
    
      const fetchData = async () =&gt; {
        const response = await fetch(&#39;https://myserver.com/data&#39;);
        const json = await response.json();
        setData(json);
      };
    
      return (
        &lt;div&gt;
          {data ? (
            &lt;ul&gt;
              {data.map((item) =&gt; (
                &lt;li key={item.id}&gt;{item.name}&lt;/li&gt;
              ))}
            &lt;/ul&gt;
          ) : (
            &lt;p&gt;Loading...&lt;/p&gt;
          )}
        &lt;/div&gt;
      );
    }

Should I try to store all the data locally? Or is it normal to make constant calls to a server? Should be React.memo involved here in some way?

答案1

得分: 1

这是非常主观的,这就是为什么您的问题被点踩的原因。话虽如此,这是我的看法:

从某种意义上说,这不是“不好的做法”,因为是的,有“更高级”的(不一定更好)方法来设计您的代码,但如果您不获取信息以供您的实时、不断变化的网站使用,那么您打算如何使其对用户保持动态呢?

您可以做些什么来改进您的代码?

首先,如果您有“静态”数据,比如用户的ID和姓名,一旦用户登录,那么您可能不需要在每次需要调用或再次显示它们时都获取这些值。您可以简单地假设只要用户已登录,并且使用有效的令牌为该用户进行请求,那么将这些信息临时保存在React.context中,然后提供给您的组件可能是一个不错的主意。

通过这样做,您还可以在登录后立即从服务器预取任何相关数据。共享的理念是应该避免不必要的获取,因为它们经常会减慢您的应用程序,因为您需要等待它们来更新您的UI。

在大多数情况下,您通常会从相同的数据服务器获取数据,这意味着您可以将您的获取调用包装到它自己的脚本文件中(或在专门用于这些内容的同一文件夹下的多个文件中),作为示例。这将允许您拥有单一的获取调用源,这意味着随着您的应用程序不断增长所需的任何更改都将始终来自相同的地方,调试也可能更容易,还将从您的组件渲染逻辑中删除不必要的混乱。

将通信(获取、套接字等)、渲染和静态数据分开是我个人在开发大型应用程序时发现有帮助的方法。这并不总是正确的,再次强调,这是非常主观的。

希望这有所帮助,如果我犯了重大错误,请随时纠正我。

英文:

This is very opinionated, that is why your question is being downvoted. That being said here is my take:

It is not "bad practice" in the sense that yes, there are "more advanced" (not necessarily better) ways to architecture your code, but if you do not fetch information to feed to your live, ever-changing website then how exactly do you intend to keep it dynamic for your users?

What could you do to improve your code ?

First, if you have "static" data like an user's id & name, once said user has logged in then you probably don't need to fetch those values every single time you need to make a call or display them again.You can simply assume that as long as an user is logged and requests are made with a valid token for that user then saving those information temporarily in a React.context that you can then provide to your components is probably a good idea.

Doing that, you can also pre-fetch any relevant data from your server right after login. It is a shared philosophy that unecessary fetch should be avoided as they often slow down your application as you are waiting for them to update your UI.

In most cases you will usually fetch from the same data server which means you could, as an exemple, start by wrapping your fetch calls into it's own script file (or multiple files under the same folder dedicated to those).
That would allow you to have a single source of fetch calls, meaning any changes required as your app grows larger will always come from the same place, debugging would arguably be much easier aswell, and it would remove unecessary clutter from your components rendering logic.

Separating communication (fetch, sockets, etc), rendering, and static data is something I, personnally, find helpfull when developping large applications. It is not always true, and again, very opinionated.

I hope this helps, and i didn't make any major mistakes be free to correct me otherwise.

huangapple
  • 本文由 发表于 2023年4月4日 15:33:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75926648.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定