首页 > 解决方案 > 在渲染之前调用 React 组件的函数

问题描述

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

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

标签: javascriptreactjs

解决方案


你应该使用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");
    }

}

推荐阅读