我正在尝试使用Django和ReactJS构建一个用于教育目的的新闻/文章网站。
目前,我已经在Django中创建了一个文章模型,并为ReactJS设置了一个API来与之交谈。每篇文章都有标题,图片,内容,精选和快速阅读属性。特色和快速读取是布尔值。我已经成功设置了我的ReactJS组件来获取所有文章,但我无法过滤article.featured
为真,article.quickreads
为真的文章。目前我的组件有三种状态:文章,精选和快速阅读。这就是它目前的样子:
class Api extends React.Component{
constructor(){
super();
this.state = {
articles: null,
featured: null,
quickreads: null
}
}
componentDidMount(){
fetch("http://127.0.0.1:8000/articles/articlesapi/").then(request => request.json()).then(response => this.setState({articles: response}))
var featured = this.state.articles.filter(article => article.featured === true)
var quickreads = this.state.articles.filter(article => article.quickreads === true)
this.setState({featured: featured, quickreads: quickreads})
}
render(){
return (
<p>Hello World</p>
)
}
}
虽然该组件获取了所有文章,但无法更新featured
和quickreads
。我收到以下错误:
Uncaught TypeError: Cannot read property 'articles' of undefined at componentDidMount (eval at <anonymous>)...
为什么会这样?
答案 0 :(得分:6)
fetch
是异步的,因此当您尝试将其过滤为设置状态时,articles
未设置(并且为null
)。而是等到获取数据:
fetch("http://127.0.0.1:8000/articles/articlesapi/")
.then(request => request.json())
.then(response => {
this.setState({
articles: response
featured: response.filter(article => article.featured === true),
quickreads: response.filter(article => article.quickreads === true)
});
});
在获取数据后过滤并设置状态以及设置articles
。但是,我只会将articles
存储在状态中,并在需要时进行过滤,最终不必同步所有数组以确保它们具有相同的数据。