在fetch中使用setState时接收错误以设置响应数据和状态

时间:2018-06-12 02:00:55

标签: reactjs fetch loading wordpress-rest-api setstate

我对React比较陌生,我正在尝试调用WordPress API在我的主页上显示精选帖子。我想在获取请求返回精选文章之前显示加载图标。如果我只是使用:

this.setState({
   feature: feature
});
在获取响应中,功能文章成功返回并显示。当我添加:

this.setState({
   feature: feature,
   isloading: false
});

我在控制台收到错误,整个应用程序爆炸了。

invariant.js:42 Uncaught (in promise) Error: Objects are not valid as a React child (found: object with keys {featureProject}). If you meant to render a collection of children, use an array instead.

以下是上下文的完整组件:

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import Loader from './../Loader.js';

import './../../../styles/home.scss';

class Home extends Component {

constructor() {
    super();
    this.state = {
        feature: [],
        articles: [],
        isloading: true
    }
}

componentDidMount() {

    let featureUrl = ' myURL /wp-json/wp/v2/projects?featured_case_study=1';
    fetch(featureUrl)
    .then(response => response.json())
    .then(response => {
        const feature = response.filter(feature => feature.acf.featured_case_study === true);
        this.setState({
            feature: feature,
            isloading: false
        });
    })

    let articlesUrl = ' myURL /wp-json/wp/v2/posts?per_page=4';
    fetch(articlesUrl)
    .then(response => response.json())
    .then(response => {
        this.setState({
            articles: response
        });
    });

}

render() {

    let isloading = this.state.isloading;

    let featureProject = this.state.feature.map((feature, index) => {
        return (
            <div className="hero" key={index} style={{ backgroundImage: `url(${feature.acf.featured_image.url})` }} >
                <div className="container">
                    <div className="row">
                        <div className="col s12 m8 l6">
                            <p className="projectType">Case Study</p>
                            <h2>{feature.title.rendered}</h2>
                            <h3 dangerouslySetInnerHTML={ {__html: feature.acf.lead_in} } />
                            <Link to={`/case-studies/${feature.slug}`} className="btn grey lighten-5">View Case Study</Link>
                        </div>
                    </div>
                </div>
            </div>
        )
    })

    let articles = this.state.articles.map((article, index) => {
        return (
            <li key={index}>
                <h5>
                    <Link to={`/articles/${article.slug}`}>
                        {article.title.rendered}
                   </Link>
                </h5>
                <span dangerouslySetInnerHTML={ {__html: article.excerpt.rendered} } />
            </li>
        )
    })

    return (
        <div className="home">

            {isloading ? (
                <Loader />
            ) : ( 
                {featureProject}
            )}

            <div className="container">
                <div className="about row">
                    <h3>User Experience Design, Usability Research <br/>&amp; Frontend Engineering </h3>
                    <h4>We drive business growth by creating digital products and services that are guaranteed to improve your bottom line. We combine an understanding of leading edge technology with a user-centered and collaborative design methodology to create valuable, usable and streamlined software.</h4>
                </div>
                <div className="row">
                    <h3>Recent Articles</h3>
                    <ul className="list">
                       {articles}
                    </ul>
                </div>
            </div>
        </div>
    );

}

};

export default Home;

使用这种方式的代码,我看到加载图标,因为它在状态下最初设置为true,但是当fetch返回精选文章时,那就是我收到错误和应用程序崩溃的时候。

2 个答案:

答案 0 :(得分:1)

您不需要featureProject周围的括号。它应该是:

        {isloading ? (
            <Loader />
        ) : ( 
            featureProject
        )}

答案 1 :(得分:1)

括号用于JSX语法。删除它们:

{isloading ? (
  <Loader />
) : 
  featureProject
}

此外,如果您不使用多行,也可以将其从JSX中删除:

{isloading ? <Loader /> : featureProject}