javascript - React.js 中的奇怪错误——Fetch API 正在从 index.html 返回 HTML,尽管没有被调用

标签 javascript reactjs text components fetch-api

我正在 React.js 中开发一个小程序。我目前正在处理程序中的一个奇怪错误。基本上,我使用 Fetch API 从文本文件中获取文本,以便可以对其执行功能。但是每当我尝试调用文本文件时,我只是不断从我的index.html 文件中获取一个充满html 标签的数组...根本没有被调用。

对于为什么会发生这种情况以及如何从sample.txt 获取正确的结果有什么建议吗?

这是我的代码: 样本.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数组?)Results

最佳答案

能够重新创建。这对你有用:

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

基本上,您仍然需要导入文件,然后将其传递给获取函数。

希望这有帮助。

关于javascript - React.js 中的奇怪错误——Fetch API 正在从 index.html 返回 HTML,尽管没有被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50417313/

相关文章:

javascript - Chrome,jquery 动画摆动

reactjs - React更新父组件状态不会重新渲染子组件

javascript - React - 从函数更改路线

javascript - wp_customize- 自定义设置未保存

javascript - Highcharts - 多个 yAxis,每个都有自己的工具提示

c++ - INFO 解析器,属性树 - 我如何根据单个键收集所有值

javascript - 如何使用 d3.js 沿着弧内的 textPath 居中(水平和垂直)文本?

text - 使用@font-face 时,SVG 文本边界框因浏览器而异?

javascript - ReactJS:操作 redux 后不重新渲染

reactjs - 如何在 React 15 中创建默认为空的受控输入