从状态API设置提取的数据将不起作用

ele*_*912 3 javascript asynchronous reactjs fetch-api

我正在尝试使用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>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

虽然组件获得所有的文章就无法更新featuredquickreads.我收到以下错误:

Uncaught TypeError: Cannot read property 'articles' of undefined at componentDidMount (eval at <anonymous>)...
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

Li3*_*357 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)
    });
  });
Run Code Online (Sandbox Code Playgroud)

并且articles在获取数据后过滤和设置状态以及设置.但是,我会只articles在状态下存储,并在需要时进行过滤,最终不必同步所有数组以确保它们具有相同的数据.