【问题标题】:how to link QR code to a cat photo (REACT)如何将二维码链接到猫照片(反应)
【发布时间】:2020-05-17 18:26:58
【问题描述】:

这里我有一个获取随机猫照片的 ajax 请求

import React, { Component } from 'react';
class RandomCat extends React.Component {
  constructor(props) {
    super(props)
    this.state = {}
    this.fetchRandomCatImg = this.fetchRandomCatImg.bind(this)
  }

  componentDidMount() {
    this.fetchRandomCatImg()
  }

  fetchRandomCatImg() {
    fetch("https://aws.random.cat/meow")
      .then(response => response.json())
      .then(data => {
        this.setState({
          error: null,
          ready: true,
          src: data.file
        })
      })
      .catch(error => this.setState({ error }))
  }

  render() {
    if (this.state.error) return <p>Oops, something went wrong!</p>
    if (!this.state.ready) return <p>Loading...</p>
    return <img src={this.state.src} className="cat" alt="random cat photo" />
  }
}
export default RandomCat;

在这里,我们需要制作一个 qr 图像代码,该代码链接到从该调用生成的同一张照片 这意味着我们需要将来自 cat api 的数据传递给另一个获取二维码的 ajax 调用 我试过这样做,但它给出了另一张照片(新照片)

import React, { Component } from 'react';
class QR extends React.Component {
  constructor(props) {
    super(props)
    this.state = {}
    this.fetchQR = this.fetchQR.bind(this)
  }

  componentDidMount() {
    this.fetchQR()
  }

  fetchQR() {
    fetch("https://qrtag.net/api/qr_12.svg?url=https://aws.random.cat/meow" )
      .then(response => response.json())
      .then(data => {
        this.setState({
          error: null,
          ready: true,
          src: data.file
        })
      })
      .catch(error => this.setState({ error }))
  }

  render() {
    if (this.state.error) return <p>Oops, something went wrong!</p>
    if (!this.state.ready) return <p>Loading...</p>
    return <img className="QR"src={this.state.src} alt="qrtag"/>
  }
}
export default QR;

【问题讨论】:

    标签: reactjs ajax webapi


    【解决方案1】:

    这有点不同,但你可以使用这个包: https://www.npmjs.com/package/qrcode.react

    然后您只需要进行一次 API 调用。一旦文件的 URL 处于您的状态,您将显示 QR 码,如下所示:

    <QRCode value={this.state.src} />
    

    但是如果你还想使用二维码生成器API,你需要将你刚刚抓取的猫的URL,data.fetch(this.state.src)的值传递给这个组件。

    如果你通过https://aws.random.cat/meow当然不行。

    【讨论】:

    • 好的,需要使用api生成器。
    • 你的意思是我应该将随机猫类的(this.state.src)传递给qr类?
    • 我实际上无法将数据从 RandomCat 组件传递到 QR 组件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    相关资源
    最近更新 更多