错误:对象作为React子对象无效(找到:密钥为{rendered,protected}的对象)。如果要渲染子级集合,请改用数组。
我收到此错误。我正在遵循一个教程,并且一切工作都很好,直到尝试渲染{content,link,title}。现在我得到这个错误。有人知道为什么吗?
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;
答案 0 :(得分:0)
随便监听您的API响应。 content
似乎是一个不能用作React子对象的对象({}
中的东西)。字符串很好。
例如,这应该起作用:
<h1>{content.rendered}</h1>
<h1>{link}</h1>
<h1>{title}</h1>