【问题标题】:Gatsby Replace Static Query Data at RuntimeGatsby 在运行时替换静态查询数据
【发布时间】:2020-11-02 02:07:29
【问题描述】:

我是 Gatsby 和 React 的新手,我正试图弄清楚如何充分利用预渲染和动态数据这两个领域。

单独的查询非常适合在构建时获取数据并将其作为道具传递给呈现每个菜单项的菜单组件。但是,在运行时,我想再次从数据库中提取数据并让它更新数据,例如,如果有价格变化等。

我知道我可以重建整个项目,但我希望将其作为后备。

如何让查询将数据发送到菜单组件,然后在数据库调用完成后[再次发送数据?]。

当前未按预期工作的代码:

index.jsx

import React, { useEffect } from "react"

import Layout from "../components/layout"
import SEO from "../components/seo"

import Menu from '../components/menu'
import { graphql } from "gatsby"

import firebase from "gatsby-plugin-firebase"
const IndexPage = (props) => {



  useEffect(() => {
    // use this hook to make db call and re-render menu component with most up to date data

    var db = firebase.firestore();
    let docs = []
    db.collection(`public/menu/${process.env.restaurantId}`).get().then(val => {

      val.forEach(doc => {
        docs.push({ node: doc.data() })
      });
      console.log('docs', docs)
      props.data.allMenuItem.edges = docs;  // i have no idea what i'm doing
    })


  }, [])


  return (
    <Layout>
      <SEO title="Home" />
      <Menu menuItems={props.data.allMenuItem.edges}></Menu>
    </Layout>
  )
}

// use this query for prerendering menu items
export const query = graphql`
query MyQuery   {
  allMenuItem {
    edges {
      node {
        available
        name
        group
      }
    }
  }
}
`;

export default IndexPage

【问题讨论】:

    标签: reactjs gatsby


    【解决方案1】:

    你不应该修改 React 属性;任何可以改变的值都应该是组件状态的一部分。见Can I update a component's props in React.js?

    但是,下面的代码应该可以做到。创建一个状态并将其属性值作为默认值。然后在客户端加载数据后更新它。

    const IndexPage = props => {
      const [menuItems, setMenuItems] = useState(props.data.allMenuItem.edges.map(({node}) => node))
    
      useEffect(() => {
        // use this hook to make db call and re-render menu component with most up to date data
        let db = firebase.firestore()
    
        db.collection(`public/menu/${process.env.restaurantId}`)
          .get()
          .then(setMenuItems)
      }, [])
    
      return (
        <Layout>
          <SEO title="Home" />
          <Menu menuItems={menuItems}></Menu>
        </Layout>
      )
    }
    

    请注意,我已切换到使用从 firestore 获得的数据格式(没有 node),而不是从 Gatsby 获得的数据格式,因此您需要修改 Menu 组件以不期望额外级别如果您使用此代码,则嵌套(使用node)。

    【讨论】:

    • 谢谢,这是一个非常干净的解决方案!我尝试实现它并不断得到一个无限循环并实现了 useEffect 中的空数组。
    猜你喜欢
    • 2020-06-13
    • 1970-01-01
    • 2022-01-02
    • 2023-03-22
    • 2021-06-02
    • 2020-11-03
    • 2020-05-04
    • 1970-01-01
    • 2020-11-30
    相关资源
    最近更新 更多