简体   繁体   中英

Strange Error in React.js — Fetch API is returning HTML from index.html, despite not being called

I'm working on a small program in React.js. I am currently dealing with a strange error in my program. Basically, I am using the Fetch API to get text out of a text file so I can perform functions on it. But whenever I try to call the text file, I just keep getting an array filled with html tags from my index.html file...which is not being called at all.

Any suggestions as to why this is happening, and how to get the correct results from sample.txt?

Here's my code: sample.txt

This is 
a sample
file.

App.js

import React, { Component } from 'react';
import Sample from './components/Sample';

class App extends Component {
    getSample = async (e) => {
      e.preventDefault();
      fetch('sample.txt')
       .then((response) => response.text())
       .then(data => {
        let sampleArray = data.split(/\r?\n/)
        console.log(sampleArray)
      })
    }
  render() {
    return (
      <div>
      <Sample
        getSample={this.getSample}
        />
      </div>
    );
  }
}

export default App;

component/Sample.js (when button is pressed, api call is made)

import React from 'react';

class Sample extends React.Component {
    render() {
        return (
            <form onSubmit={this.props.getSample}>
            <button> Submit </button>
            </form>
            )
    }
}

export default Sample;

Desired Results

sampleArray = ["This is", "a sample", "file"];

Actual Results (I'm basically just getting back an array of the html in index.js?) 结果

Was able to recreate. This will work for you:

import React, { Component } from 'react';
import myTextFile from './sample.txt'

class App extends Component {
  getSample = () => {
    fetch(myTextFile)
      .then((response) => response.text())
      .then(data => {
      console.log(data)
    })
  }
  render() {
    this.getSample()
    return (
      <div>App</div>
    );
  }
}

export default App;

Here is some relevant conversation. https://github.com/facebook/create-react-app/issues/2961

Basically, you still have to import the file and then pass it to the fetch function.

Hopes this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM