文件上传反应。无法理解问题

file upload in react. not able to understand issue

您好,我需要使用 React 将一个输入字段和一个文件发送到服务器。我正在使用 class 组件。我的以下代码无法正常工作。你能检查一下吗?

下面是我的代码。

import React from 'react';
import axios from 'axios';

class FileUpload extends React.Component {
  constructor() {
    super();
    this.state = {
      selectedFile: '',
      countryCode: '',
      responseArray: [],
    };
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleInput = this.handleInput.bind(this);
  }

  handleInputChange(event) {
    this.setState({
      selectedFile: event.target.files[0],
      responseArray: [],
    });
  }

  handleInput(event) {
    this.setState({
      countryCode: event.target.value,
    });
  }

  handleSubmit(e) {
    e.preventDefault();
    if (!this.state.selectedFile) {
      alert('Please select The file');
      return false;
    }
    if (!this.state.countryCode) {
      alert('Please select The Country Code');
      return false;
    }
    const data = new FormData();

    for (let i = 0; i < this.state.selectedFile.length; i++) {
      data.append('file[]', this.state.selectedFile[i]);
    }
    data.append('countryCode', this.state.countryCode);
    alert(data.file || data.countryCode);

    let url = process.env.API_URL;

    axios.post(url, data, {}).then(
      (res) => {
        this.setState({ responseArray: res.data });
        this.resetFile();
      },
      (error) => {
        alert(error);
      }
    );
  }

  resetFile() {
    document.getElementsByName('file')[0].value = null;
  }

  render() {
    return (
      <form>
        <div className="row">
          <div className="col-md-12">
            <h1>Translation File Upload</h1>

            <div className="form-row">
              <div className="form-group col-md-8">
                <label>Please enter the country code</label>
                <input
                  type="text"
                  value={this.state.countryCode}
                  onChange={this.handleInput}
                  required
                />
              </div>
            </div>

            <div className="form-row">
              <div className="form-group col-md-8">
                <label>Select File :</label>
                <input
                  type="file"
                  className="form-control"
                  multiple
                  name="file"
                  onChange={this.handleInputChange}
                  required
                />
              </div>
            </div>
            <br />
            <div className="form-row">
              <div className="col-md-6">
                <button onClick={this.handleSubmit.bind(this)}>Upload </button>
              </div>
            </div>
            <br />
          </div>
        </div>
      </form>
    );
  }
}

export default FileUpload;

使用输入值后未调用 handleSubmit。在此之前,如果用户不输入,则会出现验证错误。我不知道msitake是什么?

你有问题:

  handleInputChange(event) {
    this.setState({
      selectedFile: event.target.files,
      countryCode: '',
      responseArray: [],
    });
  }

无论何时添加文件,都将 countryCode 设置为 '' 然后就会被

捕获
if (!this.state.countryCode) {
  alert('Please enter country code!');
  return false;
}

您应该进行两项更改才能使其正常工作

  handleInputChange(event) {
    this.setState({
      ...this.state,
      selectedFile: event.target.files,
      responseArray: [],
    });
  }

<div className="form-group col-md-8">
    <label>Please enter the country code</label>
    <input
        type="text"
        value={this.state.value}
        name="countryCode"
        onChange={(e) => { this.setState({...this.state, countryCode: e.target.value}) }}
        required
    />
</div>

setState() 合并提供的值。您不必每次都通过整个状态。 f

setState(stateChange[, callback]) performs a shallow merge of stateChange into the new state. ref


codepen 上的工作代码:

class FileUpload extends React.Component {
  constructor() {
    super();
    this.state = {
      selectedFile: '',
      countryCode: '',
      responseArray: [],
    };
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleInput = this.handleInput.bind(this);
  }

  handleInputChange(event) {
    this.setState({
      selectedFile: event.target.files[0],
      responseArray: [],
    });
  }

  handleInput(event) {
    this.setState({
      countryCode: event.target.value,
    });
  }

  handleSubmit(e) {
    e.preventDefault();
    if (!this.state.selectedFile) {
      alert('Please select The file');
      return false;
    }
    if (!this.state.countryCode) {
      alert('Please select The Country Code');
      return false;
    }
    const data = new FormData();

    for (let i = 0; i < this.state.selectedFile.length; i++) {
      data.append('file[]', this.state.selectedFile[i]);
    }
    data.append('countryCode', this.state.countryCode);
    
    alert('all good sending: '+this.state.countryCode + ' = ' + this.state.selectedFile);

    let url = process.env.API_URL;

    
  }

  resetFile() {
    document.getElementsByName('file')[0].value = null;
  }

  render() {
    return (
      <form>
        <div className="row">
          <div className="col-md-12">
            <h1>Translation File Upload</h1>

            <div className="form-row">
              <div className="form-group col-md-8">
                <label>Please enter the country code</label>
                <input
                  type="text"
                  value={this.state.countryCode}
                  onChange={this.handleInput}
                  required
                />
              </div>
            </div>

            <div className="form-row">
              <div className="form-group col-md-8">
                <label>Select File :</label>
                <input
                  type="file"
                  className="form-control"
                  multiple
                  name="file"
                  onChange={this.handleInputChange}
                  required
                />
              </div>
            </div>
            <br />
            <div className="form-row">
              <div className="col-md-6">
                <button onClick={this.handleSubmit.bind(this)}>Upload </button>
              </div>
            </div>
            <br />
          </div>
        </div>
      </form>
    );
  }
}



ReactDOM.render(
  <FileUpload />,
  document.getElementById('root')
);