我正在尝试使用 Django 和 ReactJS 构建一个用于教育目的的新闻/文章网站。
目前,我已经在 Django 中创建了一个文章模型,并为 ReactJS 设置了一个 API 来与之对话。每篇文章都有标题、图片、内容、特色和快速阅读属性。 featured 和 quickreads 是 bool 值。我已经成功地设置了我的 ReactJS 组件来获取所有文章,但是,我无法过滤具有 article.featured
为 true 和 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>)...
为什么会这样?
最佳答案
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
存储在状态中,并在需要时进行过滤,您最终不必同步所有数组以确保它们具有相同的数据。
关于javascript - 在状态下设置从 API 获取的数据将不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44873268/