我正在用React.js编写一个小程序。我目前正在处理我的程序中的一个奇怪的错误。基本上,我使用Fetch API从文本文件中提取文本,以便对其执行函数。但是每当我尝试调用文本文件时,我总是得到一个填充了来自index.html file...which的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数组?)
发布于 2018-05-19 02:49:14
能够重现。这将对您起作用:
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函数。
希望这能有所帮助。
https://stackoverflow.com/questions/50417313
复制相似问题