【问题标题】:React/Axios - Display part of URLReact/Axios - 显示部分 URL
【发布时间】:2020-01-12 01:36:20
【问题描述】:

我正在使用这个Dogs API,并希望在生成的图像中显示狗的名字。

目前,当我单击按钮生成带有相应图像链接的随机图像时,文本显示如下:

https://images.dog.ceo/breeds/basenji/n02110806_4280.jpg

我只想要basenji,而不是整个网址。

这可以在setText 函数中显示。

我怎样才能只从 URL 中获取狗的名字,而不是整个事情本身。

代码

import * as React from "react";
import { render } from "react-dom";
import axios from "axios";
import "./styles.css";

function App() {

  const [images, setImage] = React.useState("");
  const [text, setText]    = React.useState("");

  function btnClick() {

    axios
        .all([axios.get("https://dog.ceo/api/breeds/image/random"), 
              axios.get("https://dog.ceo/api/breeds/list/all")
         ]) 
        .then(axios.spread((response) => {
              setImage(response.data.message);
              setText(response.data.message);
         }))     
        .catch(err => {
            console.log("Error happened during fetching!", err);
        });
  }

  return (
    <div className = "App">
      <img    className = "Img" src={images} alt="broken"/>
      <button className = "Button" onClick = {btnClick}>Doggie!</button>
      <p>You got a {text}</p>
    </div>
  );
}

const rootElement = document.getElementById("root");
render(<App />, rootElement);

【问题讨论】:

    标签: javascript reactjs axios react-hooks


    【解决方案1】:

    虽然,不知道,但如果每个链接都像你提到的那样显示文本,解决方案之一是根据索引将文本拆分为“/”以获取品种

     .then(axios.spread((response) => {
                  setImage(response.data.message);
                  setText(response.data.message.split('/')[4]);
             }))     
    

    【讨论】:

    • 很好,已经解决了,我会接受答案的,谢谢
    【解决方案2】:

    使用正则表达式来捕获路径的品种部分。 exec 返回一个数组,其中匹配项作为第一个元素,所有捕获的组都在后面。

    const breedRegex = /breeds\/(\w+)\//i;
    
    const path = "https://images.dog.ceo/breeds/basenji/n02110806_4280.jpg";
    
    console.log(breedRegex.exec(path));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      相关资源
      最近更新 更多