生命周期可以在使用 componentDidMount() 的箭头函数中使用,并且在我尝试添加 useEffect 的唯一响应时出现错误?试图将类组件转换为功能组件。
我在下面的一个单独项目中创建了一个内容丰富的博客,并希望将我的博客添加到我的主项目中的 blog.js 页面。
有效的原创内容博客。
博客.js
import React from "react";
import "./App.css";
import { client } from "./client";
import Posts from "./components/blog/Posts";
class App extends React.Component {
state = {
articles: [],
};
componentDidMount() {
client
.getEntries()
.then((response) => {
console.log(response);
this.setState({
articles: response.items,
});
})
.catch(console.error);
}
render() {
return (
<div className="App">
<div className="container">
<header>
<div className="wrapper">
<span>React and Content</span>
</div>
</header>
<main>
<div className="blog__page">
<h1 class="blog__page__header">ZILAH MUSIC PUBLISHING NEWS</h1>
<div className="blogs">
<div className="wrapper">
<Posts posts={this.state.articles} />
</div>
</div>
</div>
</main>
</div>
</div>
);
}
}
导出默认应用程序;
我添加了一个 useEffect,现在我的状态未定义
useEffect(() => {
client
.getEntries()
.then((response) => {
console.log(response);
this.setState({
articles: response.items,
});
})
.catch(console.error);
}, []);
我复制了我以前运行的页面并希望包含我的博客,但我在转换此处输入图像描述时遇到问题
import React, { useEffect, useState } from "react";
import { Link, Redirect } from "react-router-dom";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import { client } from "../../client";
import Posts from "../../components/blog/Posts";
import "./Blog.css";
class App extends React.Component inside an arrow function
const Blog = ({ isAuthenticated }) => {
if (isAuthenticated) {
return <Redirect to="/dashboard" />;
}
useEffect(() => {
client
.getEntries()
.then((response) => {
console.log(response);
this.setState({
articles: response.items,
});
})
.catch(console.error);
}, []);
return (
<React.Fragment>
<div className="App">
<div className="container">
<header>
<div className="wrapper">
<span>React and Content</span>
</div>
</header>
<main>
<div className="blog__page">
<h1 className="blog__page__header">
ZILAH MUSIC PUBLISHING NEWS
</h1>
<div className="blogs">
<div className="wrapper">
<Posts posts={this.state.articles} />
</div>
</div>
</div>
</main>
</div>
</div>
</React.Fragment>
);
};
Bog.propTypes = {
isAuthenticated: PropTypes.bool,
};
const mapStateToProps = (state) => ({
isAuthenticated: state.auth.isAuthenticated,
});
export default connect(mapStateToProps)(Blog);