翻閱古今
2023-03-24 13:44:29
從 CSV 文件獲取數據時遇到問題。這是我的代碼:constructor(props) { super(props); this.state = { data: [], isLoading: false, }; console.log(this.state.data) // Data is gone =( }toCSV(response){ let reader = response.body.getReader(); let decoder = new TextDecoder('utf-8'); return reader.read().then(function (result) { let data = decoder.decode(result.value); let results = Papa.parse(data); let rows = results.data; return rows; }); }componentDidMount() { this.setState({ isLoading: true }); let dataNames; return fetch('url/someFile.csv') .then(response => this.toCSV(response)) .then(data => console.log(data)) // Data is here .then(data => this.setState( { data: data, isLoading: false } )); }fetch 中的輸出:(3) […]0: Array(4) [ "abc", " 1", "aha", … ]1: Array(4) [ "def", "2", "test", … ]2: Array(4) [ "ghi", "3", "something", … ]length: 6構造函數中的輸出:[]length: 0我不明白為什么this.state是空的。我知道 promise 是一個異步函數,但我認為this.setState({ data: data, isLoading: false })會將數據設置到this.state.data中,然后實現 promise。我在這里找到了這個解決方案,但我無法解決這個問題:React: import csv file and parse我也嘗試用JSON 文件來做,因為我認為問題出在我的toCSV 函數上,但結果是一樣的....fetchJSON() { fetch(`someJSONfile.json`) .then(response => response.json()) .then(response => console.log(response)) .then(data => this.setState({ data: data, isLoading: false, }) ) .catch(error => console.log(error)); }我希望你們中的一個人可能有一個想法。謝謝你的時間 :)
2 回答

拉丁的傳說
TA貢獻1789條經驗 獲得超8個贊
構造函數將只運行一次。使用 React.Component,render() 方法將在狀態更改時重新運行,檢查它:
render(){
console.log(this.state);
return <h1>Hello World</h1>
}

慕少森
TA貢獻2019條經驗 獲得超9個贊
你有一個額外.then的沒有這個數據。下面的代碼應該適合你。
componentDidMount() {
this.setState({ isLoading: true });
let dataNames;
return fetch('url/someFile.csv')
.then(response => this.toCSV(response))
.then(data => {
console.log(data)
this.setState({ data: data, isLoading: false })
})
}
另外,console.log 不在合適的地方,如果你想記錄東西來檢查它,它應該放在 setState 執行之后。
添加回答
舉報
0/150
提交
取消