簡體   English   中英

React.js中的奇怪錯誤-盡管未被調用,Fetch API仍從index.html返回HTML

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

我正在React.js中編寫一個小程序。 我目前正在處理程序中的一個奇怪錯誤。 基本上,我使用Fetch API從文本文件中提取文本,因此可以對其執行功能。 但是,每當我嘗試調用文本文件時,我都會不斷從index.html文件中獲取充滿html標記的數組……根本沒有被調用。

關於為什么發生這種情況以及如何從sample.txt獲得正確結果的任何建議?

這是我的代碼: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(當按下按鈕時,會調用api)

import React from 'react';

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

export default Sample;

所需結果

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

實際結果(我基本上只是返回index.js中的html數組?) 結果

能夠重新創建。 這將為您工作:

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;

這是一些相關的對話。 https://github.com/facebook/create-react-app/issues/2961

基本上,您仍然必須導入文件,然后將其傳遞給fetch函數。

希望這會有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM