首页 > 解决方案 > 在 React 中使用 Rest 调用将 URL 设置为超链接

问题描述

我必须使用超链接下载一些文件。单击下载链接时,将从服务器接收 URL 的值。

const [downloadEpi,setDownloadEpi] = useState({link:'',name:''});


const premiumDownload=(email,epiId,quality)=>{

        const download ={
            email: email,
            episodeId: epiId,
            quality: quality
         };
 

        axios.post(`http://127.0.0.1:9094/api/tv-series/premiumDownload`,download,{
            'Content-Type':'application/json'
        }).then(res=>{
            const downloadRes = res.data;
            setDownloadEpi({link:downloadRes.downloadLink,name:downloadRes.epiName});
        }).catch(error=>{
            console.log(error);
        });
    }


    <DownloadButton  premium onClick={()=>premiumDownload('benz@gmail.com','viki_s01_e01','480p')}>
              <a href={downloadEpi.link && downloadEpi.link} download={downloadEpi.name && downloadEpi.name} className="link">download with IDM</a>
      </DownloadButton>

当我单击下载按钮时,将在实际值呈现之前使用空字符串调用链接。所以我必须点击按钮两次才能下载。

标签: javascriptreactjsrestaxiosreact-hooks

解决方案


我已经以一种方式解决了它,它会影响性能但工作正常

  1. 禁用高级下载功能并通过道具传递请求值。

  2. 在 componentDidMount 中调用端点

     useEffect(()=>{
    
         const download ={
             email: props.email,
             episodeId: props.epiId,
             quality: props.quality
          };
    
          axios.post(`http://127.0.0.1:9094/api/tv-series/premiumDownload`,download,{
             'Content-Type':'application/json'
         }).then(res=>{
             const downloadRes = res.data;
             setDownloadEpi({link:downloadRes.downloadLink,name:downloadRes.epiName});
         }).catch(error=>{
             console.log(error);
         });
    
        },[]);
    
    {下载Epi.link ? “使用 IDM 下载”:“正在加载...”}

推荐阅读