【发布时间】:2018-08-10 03:34:14
【问题描述】:
我正在构建一个具有文章索引页面的博客应用程序,您可以从那里单击文章以查看文章或编辑文章。
如果您从索引页面转到编辑页面,它工作得很好,因为我已经拥有了所有的文章状态。但是,如果我在进入编辑文章页面后刷新,我将不再拥有所有文章的状态。
这是一个问题,因为我在我的编辑文章页面的 componentDidMount 中进行了异步 recieveSingleArticle 调用,然后我 setState 所以我的表单被预填充。有一个双重渲染会导致“Uncaught TypeError: Cannot read property 'title' of undefined”错误,大概是在文章被接收到状态之前的第一次渲染期间。
class ArticleEdit extends React.Component {
constructor(props) {
super(props);
this.state = {title: "", body: "", imageFile: ""};
this.handleChange = this.handleChange.bind(this);
this.handlePublish = this.handlePublish.bind(this);
this.handleFile = this.handleFile.bind(this);
this.handleCancel = this.handleCancel.bind(this);
}
componentDidMount() {
const { article, requestSingleArticle } = this.props;
requestSingleArticle(this.props.match.params.articleID)
.then(() => {
this.setState({
title: article.title,
body: article.body,
imageFile: article.imageFile
});
});
}
...
我尝试将我的异步调用包装在“if (this.props.article)”中,但没有奏效。是否有处理此类问题的最佳方法?任何建议都非常感谢!
更新:
另一个可行的解决方案是除了 componentDidMount 之外还有一个 componentDidUpdate。如果 this.props.article 存在,则检查 componentDidMount,如果存在,则 setState。在 componentDidUpdate 中,将 setState 包装在以下条件中:
if (!prevProps.article && this.props.article)
【问题讨论】:
-
尝试将 API 调用移至
constructor;) -
您可能在使用路由器吗?您将 ArticleList 中的 id 作为道具传递给 ArticleEdit。并且当您刷新(浏览器)编辑页面时,不会获取任何数据?如果是这样,那么作为 props 传递的文章 id 将为 null 从而使 http 请求失败
-
感谢你们!添加到我的构造函数中确实起到了作用。
标签: javascript reactjs