【问题标题】:Issue Converting react class components to functional components with state is undefined问题将反应类组件转换为具有状态的功能组件未定义
【发布时间】:2021-03-05 20:14:06
【问题描述】:

生命周期可以在箭头函数中使用 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);
  }, []);

我复制了我之前运行的页面并希望包含我的博客,但我在转换enter image description here时遇到了问题

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);

【问题讨论】:

    标签: reactjs use-effect react-component react-lifecycle react-lifecycle-hooks


    【解决方案1】:

    函数组件使用useState钩子代替this.setState this.state (https://reactjs.org/docs/hooks-state.html)。

    在你的函数组件的顶部,添加这个(确保从'react'导入useState,就像你对useEffect所做的那样):

    const Blog = ({ isAuthenticated }) => {
      const [articles, setArticles] = useState([]);
      //... etc
    

    然后,代替this.setState() 使用:

    setArticles(response.items);
    

    而且,在正文中:

    <div className="wrapper">
      <Posts posts={articles} />
    </div>
    

    您的帖子标题(预期参数 accessToken)似乎与您提到的部分问题无关,因为您说您的状态未定义,这就是这个答案所要解决的问题

    【讨论】:

    • 你的意思是添加 代替
    • 是的——您将无法再在函数组件中引用this.state
    • 仍然无法在顶层调用 React Hook "useState" 错误。我仍然收到 React Hook “useEffect”的错误被有条件地调用。
    • 你放错地方了。看我的例子——它应该直接跟const Blog = ({ isAuthenticated }) =&gt; {
    【解决方案2】:

    我更新了我的代码 并收到此错误。 src\components\layout\Blog.js 第 16:35 行:有条件地调用 React Hook “useState”。在每个组件渲染中,必须以完全相同的顺序调用 React Hooks。你是否在提前返回后不小心调用了 React Hook?反应钩子/钩子规则 第 18:3 行:有条件地调用 React Hook “useEffect”。在每个组件渲染中,必须以完全相同的顺序调用 React Hooks。你是否在提前返回后不小心调用了 React Hook?反应钩子/钩子规则

    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";
    import BlogConnect from "./BlogConnect";
    
    const Blog = ({ isAuthenticated }) => {
      if (isAuthenticated) {
        return <Redirect to="/dashboard" />;
      }
    
      const [articles, setArticles] = useState([]);
    
      useEffect(() => {
        client
          .getEntries()
          .then((response) => {
            console.log(response);
            setArticles(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={articles} />
                    </div>
                  </div>
                </div>
              </main>
            </div>
          </div>
        </React.Fragment>
      );
    };
    
    Blog.propTypes = {
      isAuthenticated: PropTypes.bool,
    };
    
    const mapStateToProps = (state) => ({
      isAuthenticated: state.auth.isAuthenticated,
    });
    
    export default connect(mapStateToProps)(Blog);
    

    【讨论】:

    • 你应该编辑你的帖子——不要添加这个作为答案。 useState 行需要位于函数组件的 top,在if (isAuthenticated) 之前。请参阅我的更新答案。
    • 感谢您帮助简化问题,以便我理解。
    • 我的 componentDidMount() 和 useeffect 问题已解决,但我有一个新的预期参数 accessToken 的新错误
    • 您没有显示任何带有 accessToken 的代码。如果我的回答解决了最初的问题,我会要求您接受答案(绿色复选标记),然后开始一个新问题,显示说明其他问题所需的代码。
    • 我检查了(绿色复选标记)并添加了一个新问题。感谢您再次帮助该平台新手并获得自定义。
    猜你喜欢
    • 2021-02-21
    • 2021-02-08
    • 1970-01-01
    • 2020-07-27
    • 2020-05-22
    • 2020-11-30
    • 2020-10-17
    • 1970-01-01
    • 2022-01-11
    相关资源
    最近更新 更多