【发布时间】: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