javascript - 在渲染之前调用 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));
解决方案
你应该使用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");
}
}
推荐阅读
- python - 如何从基于另一个列表的列表中过滤元素并获取百分比
- css - 你如何堆叠CSS动画
- webpack - 何时在 Webpack 配置中使用“devServer.injectClient”?
- unity3d - 玩家速度没有立即重置
- ios - 缩放场景视图以适应屏幕
- c - 如何将用户输入复制到 C 中的结构中?
- javascript - Mongo DB.find 返回空数组
- python - GeoPandas 通过忽略一些行政区域来绘制 shapefile
- php - WooCommerce 中生成的项目(产品)表在哪里
- c# - Unity3d Animator:NullReferenceException:对象引用未设置为对象的实例