[英]How can i update fetch request in reactjs
我正在获取引号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;
第一件事是,将已获取的报价单数组存储到一个状态,这样当您要显示另一个报价单时就不需要再次获取它。
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>
呈现: <button onClick={this.fetchData}>next quote</button>
构造函数:
constructor(props) {
super(props);
this.state = {
quote: "",
author: ""
};
this.fetchData = this.fetchData.bind(this);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.