[英]How to fix “TypeError: _this is undefined”
I am building a site with Gatsby and right now I am working on creating a blog-post.js file which queries via graphql data from markdown files and create pages for each of it.我正在用 Gatsby 构建一个站点,现在我正在创建一个 blog-post.js 文件,该文件通过 markdown 文件中的 graphql 数据进行查询,并为每个文件创建页面。 It also should include Header, Footer and a predefined GridItem where the content should be rendered in.
它还应该包括 Header、Footer 和一个预定义的 GridItem,内容应该在其中呈现。
But the GridItem isn't rendered as expected due to a:但是由于以下原因,GridItem 没有按预期呈现:
"TypeError: _this is undefined".
“类型错误:_this 未定义”。
I am pretty new to Javascript and I figured already out that the problem are these two我对 Javascript 很陌生,我已经发现问题出在这两个
const post = data.markdownRemark,
{ classes, ...rest } = this.props;
because if i use just one of them all is working fine.因为如果我只使用其中一个,一切都可以正常工作。
import React from "react"
import { graphql } from "gatsby"
import GridItem from "components/Grid/GridItem.jsx";
import GridContainer from "components/Grid/GridContainer.jsx";
import Footer from "components/Footer/Footer.jsx";
import Header from "components/Header/Header.jsx";
import HeaderLinks from "components/Header/HeaderLinks.jsx";
import Parallax from "components/Parallax/Parallax.jsx";
import classNames from "classnames";
export default ({ data }) => {
const post = data.markdownRemark,
{ classes, ...rest } = this.props;
return (
<div>
<Header
brand="diemax"
rightLinks={<HeaderLinks />}
fixed
color="transparent"
changeColorOnScroll={{
height: 400,
color: "white"
}}
{...rest}
/>
<Parallax small filter image={require("assets/img/profile-bg.jpg")} />
<div className={classNames(classes.main, classes.mainRaised)}>
<div>
<div className={classes.container}>
<GridContainer justify="center">
<GridItem xs={12} sm={12} md={6}>
<div className={classes.title}>
<h1>{post.frontmatter.title}</h1>
</div>
<div dangerouslySetInnerHTML={{ __html: post.html }} />
</GridItem>
</GridContainer>
</div>
</div>
</div>
<Footer />
</div>
)
}
export const query = graphql`
query($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
html
frontmatter {
title
}
}
}
`
Problem is here问题就在这里
{ classes, ...rest } = this.props;
You use functional component.您使用功能组件。 So you don't have reference to component instance in this.
因此,您在此没有对组件实例的引用。 You have to
access
props as below:您必须按以下方式
access
道具:
export default ({ data, props }) => {
const post = data.markdownRemark,
{ classes, ...rest } = props;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.