当前位置:网站首页>SSG framework Gatsby accesses the database and displays it on the page

SSG framework Gatsby accesses the database and displays it on the page

2022-07-26 09:40:00 Poker_ Xu

Preface

For some front-end projects that do not change forever , Such as personal blog 、 The company's official website , Possible technology selection is SSG The framework will be relatively better than the previous CSR It would be better , It will be faster , Recently, I have studied Gatsby frame , It feels good , Just write a simple access with it MySQL database , And display a dome Record the learning experience

step

1、 install Gatsby-cli The scaffold

npm install -g gatsby-cli

2、 adopt Gatsby-cli Scaffold create a new project

gatsby new gatsby-site

among gatsby-site Is the project name , Take whatever you like

3、 Enter the project root directory and download MySQL plug-in unit

cd gatsby-site && npm install gatsby-source-mysql

4、 modify Gatsby The configuration file (gatsby-config.js), Add the plug-in

 Insert picture description here

{
    
      resolve: `gatsby-source-mysql`,
      options: {
    
        connectionDetails: {
    
          host: 'localhost',
          user: 'root',
          password: 'root',
          database: 'gatsby'
        },
        queries: [
          {
    
            statement: 'SELECT * FROM goods',
            idFieldName: 'id',
            name: 'goods', //  This is not the table name , Don't confuse 

          }
        ]
      }
    },

5、 open src/pages/index.js file , Modify the code

Of course I use one here mantine Component library for , Just to look good , You may need to know graphql grammar

import * as React from "react"
import {
     graphql } from "gatsby"

import {
     Table } from '@mantine/core';

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



const IndexPage = ({
      data }) => {
    
  return (
    <Layout>
      <Seo title="Home" />
      <Table striped >
        <thead>
          <tr>
            <th>id</th>
            <th> Price </th>
            <th> place </th>
            <th> Release time </th>
          </tr>
        </thead>
        <tbody>
          {
    data.allMysqlGoods.edges.map(({
      node }) =>
          (<tr key={
    node.mysqlId}>
            <td>{
    node.mysqlId}</td>
            <td>{
    node.price}</td>
            <td>{
    node.place}</td>
            <td>{
    node.push_time}</td>
          </tr>)
          )
          }
        </tbody>
      </Table>
    </Layout>
  )
}

/*  This is a graphql grammar , In fact, when the project starts , In the process of building ,Gatsby I will add it through the plug-in   The configuration file we added before , To connect your MySQL, Then query the result , And then through graphql  Grammar to filter out mysql The results found by the plug-in , Because there are other plug-ins in the template , Such as  `gatsby-plugin-sharp`、`gatsby-plugin-image` wait , What they find out is   Their ,mysql What the plug-in finds out is mysql Query results of  */
export const query = graphql`{ allMysqlGoods { edges { node { id name place price push_time mysqlId } } } } `

export default IndexPage

This is my gatsby database as well as goods surface
 Insert picture description here

6、 Start project

npm run develop  perhaps  gatsby develop

Access the default port 8000, See the effect
 Insert picture description here

Summary and reflection

ask : Why learn this ? Was it before vue perhaps react For written items axios Request data , Can't you achieve the above effect by displaying it on the page again ?

answer : First of all, learning this is not for new technology , No dice , Don't understand its value , It's no use learning , You might as well lie flat ;

Next, write a spa application , The general process is axios Send a request to the back end -> Back end receives request , Connect mysql -> Find out the result , Respond to the front end -> The front end receives data -> Through the framework diff Algorithm , obtain html, Render to page ;

But you think about a question that , In the above process , Start when the request is sent , Go to the framework to help you parse the data into html, Rendering to the page ends , This intermediate process , Is there no data on your page ? Is it quite blank ? If the blank is too long , As a user , He may not know to go through the above process , He only knows “ Your website is so slow , I clicked query , Why can't I get the data for half a day ”, Then as a developer, you can only pass loading Animation , perhaps Skeleton screen Something like that : User website is requesting data , Please be patient …

That's why there is SSG(Static Site Generation) Static site generation , and Gatsby Is one of the technologies of this framework , That is, I connect to the database when the project is built , Or request other resources 、 data , Then put these data into a json file , Then read this directly json file , Put the corresponding html Put it on the page , When users visit this page , In fact, it is a complete data html 了 , So soon , Users don't have to wait for others js The file is loaded or executed , You can see the page , There will be no blank pages

Of course, it is not so perfect , There must be shortcomings , For example, for frequent data interaction , This is obviously a bad plan , Because after the project is built , that json file Is dead , Is static , And analyzed html Just read this json file The data in , If the data changes after a second , At this time, the page is still old data , It will mislead users , You can only rebuild to get new data again .

原网站

版权声明
本文为[Poker_ Xu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/207/202207260936490306.html