我正在 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"];
最佳答案
能够重新创建。这对你有用:
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/