【问题标题】:Call React component's function before its render在渲染之前调用 React 组件的函数
【发布时间】:2020-06-13 13:27:57
【问题描述】:

我需要从数据库加载文章并将其设置为组件的状态。那么这篇文章应该显示在页面上。但是当我尝试这样做时,会出现错误,即加载文章的状态值未定义。所以,我认为出现问题是因为在组件渲染之后调用了加载数据函数。如何在渲染前调用此函数并正确显示状态值?

import React from 'react';
import axios from 'axios';  
import { connect } from 'react-redux';
import { withRouter } from "react-router";

class ArticlePage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      article: null,
    }
  }

  componentDidMount() {
    const { onLoad } = this.props;

    // gets full list of articles
    axios('http://localhost:8080/api/articles')
      .then((res) => onLoad(res.data))
  }

  getArticle() {
    // gets current article
    // ...
  }

  render() {

    this.getArticle();
    const { article } = this.state;

    return (
      <div>
      <h1>
        {article.title}
      </h1>
      </div>
    );
  }
}

const mapStateToProps = state => ({
  articles: state.home.articles,
});

const mapDispatchToProps = dispatch => ({
  onLoad: data => dispatch({ type: 'HOME_PAGE_LOADED', data }),
  onDelete: id => dispatch({ type: 'DELETE_ARTICLE', id }),
  setEdit: article => dispatch({ type: 'SET_EDIT', article }),
});

export default connect(mapStateToProps, mapDispatchToProps)(withRouter(ArticlePage));

【问题讨论】:

  • 在渲染中获取console.log(this.props non state)并检查数据是否存在

标签: javascript reactjs


【解决方案1】:

您没有为article 设置状态,因此您似乎在getArticles 中获得了article 的值。您还在渲染中调用getArticles,这将导致重新渲染,从而导致您进入无限循环。

除了做{ article &amp;&amp; article.title }等检查,

因此,在 componentDidMount 中,在执行 fetch 后调用 getArticles 函数。

componentDidMount() {
    const { onLoad } = this.props;

    // gets full list of articles
    axios('http://localhost:8080/api/articles')
      .then((res) => {
       onLoad(res.data);
       // call getArticles here.
       getArticles() {
        // code ...
       }
      })
  }

【讨论】:

    【解决方案2】:

    你应该使用componentWillMount

    async componentWillMount() {
        const {onLoad} = this.props;
    
        // gets full list of articles
        try {
            const res = await axios('http://localhost:8080/api/articles');
            onLoad(res.data);
        } catch (e) {
            console.log(e, "error");
        }
    
    }
    

    【讨论】:

      【解决方案3】:

      你是doing nothing wrong。您只需要在渲染组件之前执行检查,以避免初始 null 值:

      { article && article.title }
      

      另外,你也可以定义空值:

      this.state = {
        article: {
          title: ''
        }
      }
      

      啊,@gdh 也指出,您正在渲染挂钩内进行函数调用。相反,您应该在 componentDidMount 挂钩中调用该函数。

      【讨论】:

        猜你喜欢
        • 2021-01-06
        • 1970-01-01
        • 2020-09-13
        • 2019-02-21
        • 2021-10-16
        • 1970-01-01
        • 1970-01-01
        • 2022-11-16
        • 2021-04-04
        相关资源
        最近更新 更多