亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 react.js 中使用 promise 獲取數據。狀態為空。為什么?

在 react.js 中使用 promise 獲取數據。狀態為空。為什么?

翻閱古今 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>

}


查看完整回答
反對 回復 2023-03-24
?
慕少森

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 執行之后。


查看完整回答
反對 回復 2023-03-24
  • 2 回答
  • 0 關注
  • 282 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號