我最近开始使用盖茨比( Gatsby ),在理解其中的一些概念(实际上可能来自于React)方面遇到了一些困难。
例如:我正在为I18n使用一个名为gatsby插件-intl的插件,我很难理解如何将文档中的代码放入代码中。
我从初学者包中获得的代码包含了src/pages/index.js中这样的代码文件
import React from "react";
class RootIndex extends React.Component {
render() {
return (
...但是,我经常会遇到这样的代码示例:
import React from "react"
const RootIndex = () => {
return (
...显然,这两种方法产生的输出是相同的。但是,当我遇到一个教程告诉我要实现这样的代码时:
import React from "react"
import { injectIntl, Link, FormattedMessage } from "gatsby-plugin-intl"
const RootIndex = ({ intl }) => {
return (
<Layout>
<SEO
title={intl.formatMessage({ id: "title" })}
/>
...我不知道如何使用定义类的第一种方法将参数intl放在哪里。这不管用
import React from "react";
import { injectIntl, Link, FormattedMessage } from "gatsby-plugin-intl"
class RootIndex extends React.Component {
render({ intl }) {
return (
<Layout>
<SEO
title={intl.formatMessage({ id: "title" })}
/>
...我希望我的描述和问题是清楚的。在这里,我缺少更简洁的知识。哪条路是正确的?
发布于 2020-11-17 06:10:53
它们在产出方面完全相同,但在性能和性能方面却不一样。它们被称为有状态组件(基于类的组件)和无状态组件(功能组件)。
通常,如果您只想呈现一个组件,我建议使用一个功能组件,因为它具有更好的性能,并使代码更清晰、更可重用,从而使您能够更好地细化功能。
另一方面,如果您使用的是一些编程模式 (BLoC、MVVM等),您可能需要创建类来保存业务逻辑,这样就可以相互扩展。
基于类的组件(状态)
componentDidUpdate、componentDidMount等)中使用。this.props (this关键字)访问它们。职能部分(无国籍)
function关键字创建。componentDidMount)不能在功能组件中使用。但是,它们允许您使用React (useState、useEffect等)来处理所有典型的生命周期好处--添加更干净和可重用的代码。参考文献:
关于您的实现,由于gatsby-plugin-intl使用内部挂钩(useIntl),下面的代码应该可以工作:
import React from "react"
import { useIntl, Link, FormattedMessage } from "gatsby-plugin-intl"
const RootIndex = (props) => {
const intl = useIntl();
return (
<Layout>
<SEO
title={intl.formatMessage({ id: "title" })}
/>
...您缺少了允许代码使用const intl = useIntl();国际化的gatsby-plugin-intl。而不是通过props传递它,一旦您导入它,您需要在return语句之上执行它。
发布于 2022-02-23 10:45:19
同样的问题,尝试在location和crumbLabel变量中添加Layout.js
添加
this.state = {
location: props.location,
crumbLabel: props.crumbLabel,
};和
const { location } = this.state;
const { crumbLabel } = this.state;对我来说很有用。
示例代码
src/pages/index.js
import React from 'react';
import Layout from '../components/Layout';
const IndexPage = ({location}) => (
<Layout location={location} crumbLabel="Home">
...
</Layout>
);
export default IndexPage;src/components/Layout.js
import React, { Component } from 'react';
import { Breadcrumb } from 'gatsby-plugin-breadcrumb';
class Layout extends Component {
constructor(props) {
super(props);
this.state = {
location: props.location,
crumbLabel: props.crumbLabel,
};
}
render() {
const { location } = this.state;
const { crumbLabel } = this.state;
return (
<Breadcrumb location={location} crumbLabel={crumbLabel} />
);
}
}
export default Layout;https://stackoverflow.com/questions/64867636
复制相似问题