这是我关于stackoverflow的第一个问题!:所以,我正在尝试学习react,我必须做一个应用程序,在点击按钮时生成随机引用。我在尝试从api获取数据并将其传递到组件状态时遇到问题。我在互联网上搜索了一下,但我能找到的只是,在react中,大多数api调用都是在componentdidmount内部进行的,但这一点都没有帮助。每次单击按钮时,我都需要调用端点。编辑:我必须提到,我正在使用codepen.io进行此操作。也许问题与此有关。这里是链接(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"));
1条答案
按热度按时间qcuzuvrc1#
我试过你的代码,代码看起来不错。我认为问题在于您使用的api url。试着用这个代替https://api.quotable.io/random. 现在可以了