【问题标题】:How can i update fetch request in reactjs我如何在reactjs中更新获取请求
【发布时间】:2019-06-07 07:30:37
【问题描述】:

我正在获取报价 API。在这里,我想随机更新引号,但我想在单击按钮时更新引号。我不知道该怎么做。谁能帮我这样做?

我已使用 fetch request 获取数据,然后将数据添加到 state。

这是我的代码

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.fetchData 呢?还是在第一次调用时存储所有的引号,这样就可以生成一个新的随机索引而不需要另一个网络调用?

标签: javascript reactjs api fetch


【解决方案1】:

首先,将您获取的报价数组存储到一个状态,这样当您想要显示另一个报价时就不需要再次获取它。

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
   });
}

在您的 fetch 函数中,将您获取的数组存储到状态,然后在之后调用 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>

【讨论】:

    【解决方案2】:

    渲染:&lt;button onClick={this.fetchData}&gt;next quote&lt;/button&gt;

    构造函数:

    constructor(props) {
      super(props);
      this.state = {
        quote: "",
        author: ""
      };
      this.fetchData = this.fetchData.bind(this);
    }
    

    【讨论】:

    • 谢谢你其实我忘了绑定函数这就是为什么我得到无限循环可能是。
    • 这不是一个好主意,因为每次按钮点击都会不必要地获取新数据。检查我的回答如何正确地做到这一点
    猜你喜欢
    • 2020-07-17
    • 1970-01-01
    • 2020-01-17
    • 2020-10-26
    • 2016-12-01
    • 2019-03-03
    • 2020-02-13
    • 1970-01-01
    • 2021-03-29
    相关资源
    最近更新 更多