首页 > 解决方案 > 如何在反应js中调用或将值从一个js文件传递到另一个文件

问题描述

我对 Reactjs 世界完全陌生,

如何从 exportExcelPage.js 调用选定的“start_date”和“end_date”到 exportAPICall.js 文件。

我在exportExcelPage.js中创建了日期字段,我需要将这些字段值传递给exportAPICall.js文件。

我试图通过如下函数: exportExcelPage.js

{
            startDate && endDate && 
            <Button id="button" variant="contained" size="large" className={classes.button} startIcon={<CloudDownloadIcon />} onClick={exportAPICall(startDate, endDate)}>
              {DOWNLOAD}
            </Button>
          }

导出APICall.js

export default function exportAPICall(startDate, endDate){
.............
}

之后能够在控制台中获取日期值,但问题是当我自动选择 endDate 时,它​​会触发 api 调用,而无需单击 downlad 按钮。

请帮助我,如何在exportAPICall.js文件中调用这两个字段。

导出ExcelPage.js

import React, { useState } from "react";

//styles
import "../../styles/App.css";
import "react-datepicker/dist/react-datepicker.css";

//imports
import DatePicker from "react-datepicker";
import addMonths from 'date-fns/addMonths';
import format from 'date-fns/format';
import exportImage from '../../images/exportImage.jpg';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import CloudDownloadIcon from '@material-ui/icons/CloudDownload';
import {TITLE, NOTE_DESC, NOTE, START_DATE, END_DATE, DOWNLOAD} from '../../utilities/text';

//api call
import exportAPICall from "../../api/exportAPICall";

const useStyles = makeStyles((theme) => ({
  button: {
    margin: theme.spacing(1),
  },
}));

function ExportExcelPage() {
  const classes = useStyles();
  const [startDate, setStartDate] = useState(null);
  const [endDate, setEndDate] = useState(null);

  const handleStartDate = (date) => {
    setStartDate(date);
    setEndDate(null);
  };

  const handleEndDate = (date) => {
    setEndDate(date);
  };


  if (startDate) {
    var maxDate = startDate;
    maxDate = format(addMonths(startDate, 36), " E MMM dd yyyy HH:mm:ss ");
    var strToDate = new Date(maxDate);
    console.log("maxDate value ==" + maxDate);
    console.log("string to date value ==" + strToDate);
  }


  return (
    <div className="App" id="container">
      <div className="input-container">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"></link>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"></link>
        <script src = 'header.js'></script>
        <img src={exportImage} id="ui-image"></img>
        <div >
          <h4 id="title"><b>{TITLE}</b></h4>
          <form id="form-css">
            <DatePicker id="startDate-css" placeholderText={START_DATE} dateFormat='dd-MM-yyyy' selected={startDate} onChange={handleStartDate}/>
            <span>   <b id="dash-space">-</b>    </span>
          <DatePicker id="endDate-css" placeholderText={END_DATE} dateFormat='dd-MM-yyyy' selected={endDate} minDate={startDate} maxDate={strToDate} onChange={handleEndDate}/>
          </form>
          <p id="note"><b>{NOTE}</b><span id="space"></span>{NOTE_DESC}</p>
          {
            startDate && endDate && 
            <Button id="button" variant="contained" size="large" className={classes.button} startIcon={<CloudDownloadIcon />} onClick={exportAPICall}>
              {DOWNLOAD}
            </Button>
          }
        </div>
      </div>
    </div>
  );
}

export default ExportExcelPage;

导出APICall.js


import { formatMs } from "@material-ui/core";
import axios from "axios";
import * as moment from 'moment';
import {EXPORT_API} from '../utilities/endpoints';

export default function exportAPICall()
{
    const current_date = moment(new Date()).format("YYYY-MM-DD_HHmmss");

    let url = process.env.REACT_APP_MS_BASEURL + EXPORT_API();

    let data = {
        auth: false,
        op: "",
        currentUser : {}
    };

    let postData = {
        "Id": 190,
        "startDate" : "2021-06-01T03:48:46.174Z",
        "endDate" : "2021-06-16T03:48:46.174Z"
    }
    

    
    axios.post(url, postData, { 
        withCredentials : true
        
    })
    .then(r => {
        console.log("gettoken",r);
        data.auth = true;
        data.op = r.headers['x'];
        data.currentUser = r.data;
        //dispatch(GetActionObject(loginMod.actionType+'/'+Constants.STATUS_SUCCESS, data));
        //  setGlobalState_callback(data);

     var fileURL = window.URL.createObjectURL(new Blob([r.data]));
     var fileLink = document.createElement('a');
    
     fileLink.href = fileURL;
     fileLink.setAttribute('download', 'AdminReport_'+current_date+'.zip');
     document.body.appendChild(fileLink);
     
     fileLink.click();
        
    })
    .catch(e=>{
        console.log(e);
        if(e.response)
        {
            data.error = e.response.data;
        }
        else 
        {
            data.error = e.message;
        }
        //dispatch(GetActionObject(loginMod.actionType+'/'+Constants.STATUS_FAILED, data));
        //setGlobalState_callback(data);
    });  
 
}

export {exportAPICall}

标签: reactjsaxiosreact-hooksreact-contextreact-state

解决方案


尝试像这样调用 exportApiCall 函数,它将解决您的问题:

{
  startDate && endDate && 
  <Button
    id="button"
    variant="contained"
    size="large"
    className={classes.button}
    startIcon={<CloudDownloadIcon />}
    onClick={() => { exportAPICall(startDate, endDate) }}
  >
    {DOWNLOAD}
  </Button>
}

您需要将函数传递给 onClick 而不是调用它。当点击事件被触发时,该函数将被调用。


推荐阅读