我正在获取引号API。在这里,我想随机更新报价,但是在单击按钮时我想更新报价。我不知道该怎么做。有人可以帮我吗?
我已经使用获取请求获取了数据,然后将数据添加到状态中。
这是我的代码
import React from "react";
import "./styles.css";
class Box extends React.Component {
constructor(props) {
super(props);
this.state = {
quote: "",
author: ""
};
}
componentDidMount() {
this.fetchData();
}
fetchData = () => {
fetch(
"https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json"
)
.then(result => {
return result.json();
})
.then(data => {
const ran = Math.floor(Math.random() * data.quotes.length);
console.log(data.quotes[ran].quote);
console.log(data.quotes[ran].author);
this.setState({
quote: data.quotes[ran].quote,
author: data.quotes[ran].author
});
});
};
render() {
return (
<div id="quote-box" className="container">
<div className="box-container">
<div className="text-center">
<h1 id="text">{this.state.quote}</h1>
</div>
<div className="float-right">
<p id="author">
<span>- </span>
{this.state.author}
</p>
</div>
</div>
<div className="box-item">
<div className="row">
<div className="col-sm-6">Twitter</div>
<div className="col-sm-6">
<button>next quote</button> <--- Here i want this button to update quotes on screen.
</div>
</div>
</div>
</div>
);
}
}
export default Box;
答案 0 :(得分:2)
第一件事是,将已获取的报价单数组存储到一个状态,这样,当您要显示其他报价时,就无需再次获取它。
this.state = {
quoteArray: [], <----- This one
quote: "",
author: ""
};
然后创建一个单独的函数,该函数将从那个quoteArray中获取随机报价
pickRandomQuote = () => {
const ran = Math.floor(Math.random() * data.quotes.length);
this.setState({
quote: this.state.quoteArray[ran].quote,
author: this.state.quoteArray[ran].author
});
}
在获取函数中,将获取的数组存储到状态,然后在之后调用pickRandomQuote
fetchData = () => {
fetch(
"https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json"
)
.then(result => {
return result.json();
})
.then(data => {
this.setState({
quoteArray: data
});
this.pickRandomQuote();
});
};
然后生成新的随机报价,只需将其放在您的按钮中
<button onClick={() => this.pickRandomQuote()}>next quote</button>
答案 1 :(得分:1)
渲染:<button onClick={this.fetchData}>next quote</button>
构造函数:
constructor(props) {
super(props);
this.state = {
quote: "",
author: ""
};
this.fetchData = this.fetchData.bind(this);
}