【问题标题】:Fetch data with promise in react.js. State is empty. Why?在 react.js 中使用 promise 获取数据。状态为空。为什么?
【发布时间】:2021-01-10 18:47:04
【问题描述】:

从 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 然后承诺就实现了。

我在这里找到了这个解决方案,但我无法解决这个问题: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));
    }

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

【问题讨论】:

  • 构造函数在componentDidMount之前被调用。您正在使用一个空数组初始化 data 并立即记录它...为什么您期望看到在不同时间调用的完全不同函数中设置的值?
  • 哦,这么简单的解决方案。这解决了我的问题。我按照 Peter 的建议将 console.log 放入渲染函数中,现在数据就在那里。谢谢。

标签: javascript reactjs


【解决方案1】:

构造函数只会运行一次。使用 React.Component,render() 方法将在状态更改时重新运行 检查它:

render(){
 console.log(this.state);
 return <h1>Hello World</h1>
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2017-11-29
      • 2020-08-25
      • 1970-01-01
      • 2021-01-30
      • 1970-01-01
      • 2022-11-19
      • 1970-01-01
      • 2019-03-18
      • 1970-01-01
      相关资源
      最近更新 更多