首页 > 解决方案 > 在 react.js 中使用 promise 获取数据。状态为空。为什么?

问题描述

从 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));
    }

我希望你们中的一个人可能有一个想法。谢谢你的时间 :)

标签: javascriptreactjs

解决方案


你有一个额外.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 执行之后。


推荐阅读