我知道在React组件挂载之前,'window'或'document'对象是不可识别的。
我正在尝试制作一个下载按钮,该按钮从后端服务器接收处理过的Excel文件。在使用React之前,我通常会这样实现...
<button onclick="download()">Download</button>
<script>
function download() {
const URL = 'http://dynamic-link.com/sample.xlsx'
window.location.href = URL
}
</script>
然而在Next.js或React中,window对象无法被识别,因此我不得不采取其他方式。下载URL是动态的,因此我不会使用next.config.js。
pages/index.tsx
//...
const handleDownloadExcel = () => {
router.push('/download')
}
//...
return(
//...
<button onClick={() => handleDownloadExcel()}>Download!</button>
//...
pages/download.tsx
import { useEffect } from 'react'
import { useRouter } from 'next/router'
const DownloadPage = () => {
const router = useRouter();
useEffect(() => {
//I will pass this URL variable by props later on.
const URL = 'http://dynamic-url.com/sample.xlsx'
window.location.href = URL;
router.push('/')
}, [])
return (
<>
</>
)
}
export default DownloadPage;
现在我已经成功从服务器上下载了一个文件,但似乎不太对劲。有其他方法可以做到这一点吗?