在 state 中设置从 API 获取的数据将不起作用

Setting fetched data from API in state won't work

我正在尝试使用 Django 和 ReactJS 构建一个 news/article 用于教育目的的网站。

目前,我已经在 Django 中创建了一个文章模型,并设置了一个 API 供 ReactJS 与之对话。每篇文章都有标题、图片、内容、特色和快速阅读属性。 featured 和 quickreads 是布尔值。我已经成功地设置了我的 ReactJS 组件来获取所有文章,但是,我在过滤 article.featured 为 true 和 article.quickreads 也为 true 的文章时遇到了问题。目前我的组件有三种状态:文章、精选和快速阅读。这是目前的样子:

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>
    )
  }
}

尽管组件获取了所有文章,但未能更新 featuredquickreads。我收到以下错误:

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 存储在状态中,并在需要时进行过滤,最终不必同步所有数组以确保它们具有相同的数据。