[英]Call React component's function before its render
我需要從數據庫加載文章並將其設置為組件的 state。 那么這篇文章應該顯示在頁面上。 但是當我嘗試這樣做時,會出現錯誤,即加載文章的 state 的值未定義。 所以,我認為出現問題是因為在組件渲染之后調用了加載數據 function 。 如何在渲染之前調用此 function 並正確顯示狀態值?
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");
}
}
你沒有做錯任何事。 您只需要在渲染組件之前執行檢查,以避免初始 null 值:
{ article && article.title }
或者,您也可以定義空值:
this.state = {
article: {
title: ''
}
}
啊,@gdh 也指出,您正在渲染掛鈎內進行 function 調用。 相反,您應該在componentDidMount
掛鈎中調用 function 。
您沒有為article
設置 state,因此您似乎在 getArticles 中獲取article
的值。 您還在渲染中調用getArticles
,這將導致重新渲染,這將導致您進入無限循環。
除了進行{ article && article.title }
之類的檢查,
因此,在 componentDidMount 中,在執行 fetch 后調用getArticles
function。
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 ...
}
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.