How to download fetch response in react as file

后端 未结 5 1150
不知归路
不知归路 2020-12-07 21:02

Here is the code in actions.js

export function exportRecordToExcel(record) {
    return ({fetch}) => ({
        type: EXPORT_RECORD_TO_EXCEL,         


        
5条回答
  •  粉色の甜心
    2020-12-07 21:32

    I needed to just download a file onClick but I needed to run some logic to either fetch or compute the actual url where the file existed. I also did not want to use any anti-react imperative patterns like setting a ref and manually clicking it when I had the resource url. The declarative pattern I used was

    onClick = () => {
      // do something to compute or go fetch
      // the url we need from the server
      const url = goComputeOrFetchURL();
    
      // window.location forces the browser to prompt the user if they want to download it
      window.location = url
    }
    
    render() {
      return (
        

提交回复
热议问题