【发布时间】:2021-08-04 19:13:28
【问题描述】:
我是一名 React 新手,正在 FCC 上学习,我正在努力处理获取的对象。
我正在尝试构建一个基本的“随机报价机”React 组件,该组件获取(然后从其中呈现值)一个对象。对象(在 componentDidMount 中获取)有一个键 (quotes),它是一个对象数组(每个对象都有 quote 和 >author 键),然后我将此数组分配给本地状态 (quotesData),然后在 render 中作为常量。
本质上,组件应该在第一次 render 时显示一个随机引用,然后在每次单击 New Quote 按钮 时再次显示。因此,我(随机)将数组中的一个对象分配给 nextQuote。
在此之后,我遇到了问题。我可以console.log(quotesData)(和nextQuote)没有问题,但为什么我不能从存储在nextQuote中的对象分配值到 nextQuoteQuote 或 nextQuoteAuthor,使用点(或括号)表示法?
这是笔的链接(完整代码也在下面):https://codepen.io/igorgetmeabrain/pen/rNmwMEM
现在,它只是不断地向我抛出对象错误并且根本不会渲染。请帮忙!
class RandomQuotes extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isFetching: false,
quotesData: [],
random: Math.random()
};
this.getNewQuote = this.getNewQuote.bind(this);
this.fetchData = this.fetchData.bind(this);
}
fetchData() {
this.setState({isFetching: true});
fetch ('https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json',
{headers: {
Accept: 'application/json'
}})
.then(res => res.json())
.then((data) =>
{
this.setState({quotesData: data.quotes, isFetching: false});
})
.catch(error => {
console.log(error);
this.setState({isFetching: false, error: error});
});
}
getNewQuote() {
this.setState({
random: Math.random()
});
}
componentDidMount() {
this.fetchData();
}
render() {
const {quotesData, isFetching, error} = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (isFetching) {
return <div>Loading...</div>;
} else {
const randomIndex = Math.floor(this.state.random * quotesData.length);
const nextQuote = quotesData[randomIndex];
const nextQuoteQuote = nextQuote.quote;
const nextQuoteAuthor = nextQuote.author;
return (
<div id="quote-box">
<p id="text">{nextQuoteQuote}</p>
<p id="author">{nextQuoteAuthor}</p>
<button id="new-quote" onClick={this.getNewQuote}>
New Quote
</button>
</div>
);
}
}
}
ReactDOM.render(<RandomQuotes />, document.getElementById("root"));
【问题讨论】:
标签: javascript json reactjs fetch-api