[英]How do I fetch data from an endpoint everytime I click a button? In React
This is my first question on StackOverflow!这是我关于 StackOverflow 的第一个问题! :D So, I am trying to learn React and I have to do an app that generates random quotes when a button is clicked.
:D 所以,我正在尝试学习 React,我必须做一个应用程序,当单击按钮时生成随机引号。 I have a problem when trying to get data from an API and passing it to the state of the component.
尝试从 API 获取数据并将其传递给组件的状态时遇到问题。 I searched the internet but all I could found was that in React, most API calls are made inside componentDidMount , but that doesn't help at all.
我在互联网上搜索,但我能找到的只是在 React 中,大多数 API 调用是在componentDidMount内部进行的,但这根本没有帮助。 I need to make a call to the endpoint everytime the button is clicked.
每次单击按钮时,我都需要调用端点。 Edit: I have to mention that I am using codepen.io for this.
编辑:我不得不提到我为此使用了 codepen.io。 Maybe the problem is related to this.
也许问题与此有关。 Here is the link ( https://codepen.io/bogdanoprea1998/pen/abWmaWa?editors=0011 )
这是链接( https://codepen.io/bogdanoprea1998/pen/abWmaWa?editors=0011 )
const setRandomColor = () => {
const color =
"hsl(" +
360 * Math.random() +
"," +
(25 + 70 * Math.random()) +
"%," +
(85 + 10 * Math.random()) +
"%)";
$("#quote-box").css("background-color", color);
};
class QuoteApp extends React.Component {
constructor() {
super();
this.state = {
author: "Satya Nadella",
quote: "This is a software-powered world.",
};
this.handleClick = this.handleClick.bind(this);
}
//Handlers
handleClick() {
fetch("http://quotable.io/random")
.then((res) => res.json())
.then((data) => {
console.log(data);
this.setState((prevState) => {
return {
author: data.author,
quote: data.content,
};
});
});
setRandomColor();
}
componentDidMount() {
fetch("http://quotable.io/random")
.then((res) => res.json())
.then((data) => {
console.log(data);
this.setState((prevState) => {
return {
author: data.author,
quote: data.content,
};
});
});
setRandomColor();
}
//Error handling
componentDidCatch(error, errorInfo) {
console.log(error, errorInfo);
}
render() {
const tweetLink = `https://twitter.com/intent/tweet?text=${this.state.quote} -${this.state.author}`;
return (
<div id="quote-box">
<h2 id="text">{this.state.quote}</h2>
<h3 id="author">{this.state.author}</h3>
<a className="twitter-share-button" href={tweetLink} id="tweet-quote">
Tweet
</a>
<button onClick={this.handleClick} id="new-quote">
Next
</button>
</div>
);
}
}
ReactDOM.render(<QuoteApp />, document.getElementById("root"));
I've tried your code, and the code looks good.我试过你的代码,代码看起来不错。 I believe the issue is with the API URL that you use.
我相信问题出在您使用的 API URL 上。 Try to use this instead https://api.quotable.io/random .
尝试使用它代替https://api.quotable.io/random 。 It will work now
它现在会工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.