每次单击按钮时如何从端点获取数据?在反应

时间:2021-07-11 11:45:55

标签: javascript reactjs api fetch

这是我关于 StackOverflow 的第一个问题! :D 所以,我正在尝试学习 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 个答案:

答案 0 :(得分:0)

我试过你的代码,代码看起来不错。我相信问题出在您使用的 API URL 上。 尝试使用它代替 https://api.quotable.io/random。现在就可以使用了