Настройка макета в Gatsby - PullRequest
0 голосов
/ 17 июня 2020

Здравствуйте, я использую Gatsby для создания своего приложения с использованием API фондового рынка, и я новичок в Gatsby. Я пытаюсь обернуть каждую из своих страниц вокруг <Layout> </Layout>, потому что внутри моего макета. js есть верхний и нижний колонтитулы, тогда на всех моих страницах будут те же заголовок и нижний колонтитул без повторения кода. Я получаю сообщение об ошибке Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Эта ошибка связана со следующим кодом в layout.js:

import React, { Component } from "react"

import Header from "./header"
import Footer from "./footer"
import "./layout.css"


const Layout = (props) => {

  return (
    <div>
      <Header />
        {props.children}
      <Footer />
    </div>
  )
}


export default Layout

Я попытался переключить layout.js на компонент на основе класса и получил та же ошибка:

import React, { Component } from "react"

import Header from "./header"
import Footer from "./footer"
import "./layout.css"


export class Layout extends Component {
  render() {
    return (
      <div>
        <Header />
          {this.props.children}
        <Footer />
      </div>
    )
  }
}

Вот мой index.js файл:

import React from "react"
import axios from "axios"
import '../CSS/index.scss'
import Layout from "../components/layout"


export default class index extends React.Component {
    state = {
        companyName: "",
        previousClose: "",

    }

    clickHandler = (event) => {
            if (event.keyCode === 13) {
            const query = event.target.value;
            const API_KEY = '*****************';
        axios.get(`https://cloud.iexapis.com/stable/stock/${query}/quote?token=${API_KEY}`)
            .then(res => {
                const companyName = res.data['companyName'];
                this.setState({ companyName })

                const previousClose = res.data['previousClose'];
                this.setState({ previousClose })
            })
        }
    }



    render() {
        return (
            <Layout>
                <div class = "main-div">
                    <input type="search" class="main-search" onKeyDown={event => this.clickHandler(event)}/>
                    <h3>{this.state.companyName}</h3>
                    <p>{this.state.previousClose}</p>
                </div>
            </Layout>
        )
    }
}

package. json

{
  "name": "gatsby-starter-default",
  "private": true,
  "description": "A simple starter to get up and developing quickly with Gatsby",
  "version": "0.1.0",
  "author": "Kyle Mathews <mathews.kyle@gmail.com>",
  "dependencies": {
    "axios": "^0.19.2",
    "fs": "0.0.1-security",
    "gatsby": "^2.22.15",
    "gatsby-image": "^2.4.5",
    "gatsby-plugin-manifest": "^2.4.9",
    "gatsby-plugin-offline": "^3.2.7",
    "gatsby-plugin-react-helmet": "^3.3.2",
    "gatsby-plugin-sass": "^2.3.4",
    "gatsby-plugin-sharp": "^2.6.9",
    "gatsby-source-filesystem": "^2.3.8",
    "gatsby-transformer-sharp": "^2.5.3",
    "node-sass": "^4.14.1",
    "prop-types": "^15.7.2",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-helmet": "^6.0.0"
  },
  "devDependencies": {
    "prettier": "2.0.5"
  },
  "keywords": [
    "gatsby"
  ],
  "license": "MIT",
  "scripts": {
    "build": "gatsby build",
    "develop": "gatsby develop",
    "format": "prettier --write \"**/*.{js,jsx,json,md}\"",
    "start": "npm run develop",
    "serve": "gatsby serve",
    "clean": "gatsby clean",
    "test": "echo \"Write tests! -> https://gatsby.dev/unit-testing\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/gatsbyjs/gatsby-starter-default"
  },
  "bugs": {
    "url": "https://github.com/gatsbyjs/gatsby/issues"
  }
}

1 Ответ

0 голосов
/ 17 июня 2020

По умолчанию Gatsby несовместим с кодом, зависящим от fs. Скорее, Гэтсби загружает все свои данные во время процесса сборки, которые затем становятся доступными во время выполнения через GraphQL API.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...