【问题标题】:Gatsby fetch data from local storage best practiceGatsby 从本地存储中获取数据的最佳实践
【发布时间】:2023-02-06 15:03:13
【问题描述】:

每次应用程序启动时,我都想从本地存储(在运行时)获取数据,然后将其存储在商店中。

Gatsby 文档解释了执行此操作的方法: https://www.gatsbyjs.com/docs/conceptual/data-fetching/

基本上只需在页面中使用 useEffect 挂钩并从本地存储中获取数据。但是,我想独立于正在访问的页面获取这些数据。比如我在索引页上取数据,用户刷新另一个页面,就取不到数据。我想在一个普通的 React 应用程序中用相当于 App.tsx 文件的方式来做.

我目前的解决方案是在 wrap-pages 文件中进行:

const MyLocalStorage = ({ children }) => {
  const { getLocalStorage} = fromStore()

  useEffect(() => {
    getLocalStorage() // fetches data from local storage
  }, [])
  return null
}

export function wrapPagesDeep({ element }) {
  return (
    <>

        <MyLocalStorage/>
        {element}

    </>
  )
}

然而,这没有多大意义。该文件用于包装组件,而不是用于数据获取。请问这样做的正确方法是什么?

【问题讨论】:

    标签: javascript reactjs gatsby


    【解决方案1】:

    根据您的架构、设计系统和用例,有多种方法(例如,从提供者到包装器,从隔离服务到控制器等)。

    如果不知道决策中涉及的所有内容,就没有所谓的“最佳实践”:制作一些超级复杂和孤立的逻辑(如添加 MVVM:控制器、存储等)可能看起来不错,但对于简单的场景,反之亦然:对于复杂的应用程序来说,简单直接的方法可能不是一个好的解决方案。

    按照您的方法,我认为可以通过将此逻辑移至 Layout(或包装您的应用程序的包装器)并向其添加 location prop 来轻松隔离(和重用)它。就像是:

    const Layout = ({ children, location = {} }) => {
      const { getLocalStorage} = fromStore()
    
      useEffect(() => {
        getLocalStorage() // fetches data from local storage
      }, [location])
    
      return (
        <>
            <main>{children}</main>
        </>
      )
    }
    
    export default Layout
    

    然后,在每次使用Layout时:

    const SomePage = ({ location }) => {
      return (
        <Layout location={location}>
          <h1>Some content</h1>
        </Layout>
      );
    };
    

    注意:locationprop 在所有顶级组件(页面和模板)中默认继承,如您在文档中所见

    因此每次位置发生变化时,您都会获取本地存储数据。这可以很容易地移动到自动更新值的提供程序。您只需要相应地包装您的应用程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-29
      • 1970-01-01
      • 1970-01-01
      • 2018-08-14
      • 2015-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多