[英]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"];
能够重新创建。 这将为您工作:
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.