【问题标题】:Error: Objects are not valid as a React child (found: object with keys {rendered, protected})错误:对象作为 React 子对象无效(找到:带有键 {rendered, protected} 的对象)
【发布时间】:2020-03-05 18:24:19
【问题描述】:

错误:对象作为 React 子对象无效(找到:带有键 {rendered, protected} 的对象)。如果您打算渲染一组子项,请改用数组。

我收到此错误。在我尝试渲染 { content, link, ti​​tle } 之前,我一直在学习教程并且一切正常。现在我得到这个错误。有人知道为什么吗?

import React, {Component, } from 'react'

class QuoteMachine extends Component {

constructor(){
    super();
    this.state = {
         quote: {
             content: "",
             link: "",
             title: ""
         },
         hasQuote: false
    }
    this.END_POINT = 'https://quotesondesign.com/wp-json/wp/v2/posts/?orderby=rand'
}

getRandomQuote = event => {
    fetch(this.END_POINT)
    .then(response => response.json())
    .then(data => {
        console.log(data)
    if (data[0].content && data[0].title && data[0].link ) {
        let { quote } = this.state;
        let quoteData = data[0];
        quote.content = quoteData.content;
        quote.link = quoteData.link;
        quote.title = quoteData.title;
        this.setState( { quote }, () => {
            if(this.state.hasQuote === false){
                this.setState( { hasQuote: true })
            }
        }
            )
    } else {
        console.error("no quote")
    }})
}

renderQuote = () => {
    const { title, content, link } = this.state.quote;

    return(
        <div>
            <h1>{content}</h1>
            <h1>{link}</h1>
            <h1>{title}</h1>


        </div>
    )
}

render () {
    const { hasQuote } = this.state; 
    console.log(this.state);
    console.log("yahbro")
    return (

        <React.Fragment>
            <h1>Quote Machine</h1>
            <button onClick={this.getRandomQuote }>Click For New Quote</button>
            <br></br>
            { hasQuote === true ? 
            this.renderQuote()
            : "no quote yet" }
        </React.Fragment>
    )
}
}

export default QuoteMachine;

【问题讨论】:

  • 看看content 长什么样会很有趣。
  • 我猜它是一个对象。
  • 你能发一个教程的链接吗?

标签: reactjs


【解决方案1】:

冒昧地窥探您的 API 响应。 content 似乎是一个不能用作 React 子对象的对象({} 内部的东西)。字符串很好。

例如,这应该可以工作:

<h1>{content.rendered}</h1>
<h1>{link}</h1>
<h1>{title}</h1>

【讨论】:

    猜你喜欢
    • 2021-03-08
    • 2021-05-19
    • 2018-01-12
    • 2020-02-27
    • 2022-01-05
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    • 2020-12-28
    相关资源
    最近更新 更多