【问题标题】:React doesn't render data coming from an api responseReact 不会渲染来自 api 响应的数据
【发布时间】:2018-08-04 07:27:28
【问题描述】:

我看到了很多问题,但我无法找到解决方案 这是我的代码:

import React, { Component } from "react";
import axios from "axios";
import "./tree.css";
import "./mainTree";

class TablesTree extends Component {
  constructor(props) {
    super(props);
    this.data = this.props.info;
    this.state = {
      fields: [],
      data: [],
      show: false
    };
  }

  componentDidMount() {
    var dataGet = [];
    this.props.tables.forEach((name, i) => {
      this.getFieldsTable(name.TABLE_NAME, (err, res) => {
        if (res) {
          dataGet.push({
            TABLE_NAME: name.TABLE_NAME,
            columns: res
          });
        }
      });
    });
    this.setState({ data: dataGet });
  }
  getFieldsTable(table, callback) {
    axios
      .get(`table/columns?name=${this.data.user}&psw=${this.data.password}&schema=${this.data.schema}&table=${table}`)
      .then(response => {
        callback(null, response.data);
      })
      .catch(error => {
        console.log(error);
      });
  }

  render() {
    return (
      <div>
        {this.state.data
          ? this.state.data.map((itm, i) => {
              return (
                <div>
                  <h1>{itm.TABLE_NAME}</h1>
                </div>
              );
            })
          : null}
      </div>
    );
  }
}

export default TablesTree;

我已经制作了 this.state.data 的 console.log 并且数据在那里,但它没有呈现任何东西 我已经尝试了很多解决方案,但我仍然没有渲染数据,我会感谢你的帮助。

【问题讨论】:

  • getFieldsTable 是异步的,所以dataGet 会在你做this.setState({data: dataGet}); 时为空

标签: reactjs axios


【解决方案1】:

我要对您的代码进行一些更改,但最重要的是,您需要在推送到 dataGet(在回调函数内部)之后执行 this.setState

因为您的 API 调用是异步的,所以您只在最初安装组件时调用 setState 一次(而 dataGet 仍然为空)。

【讨论】:

  • 你不知道我对你所有的答案有多感激,这个错误我已经有 2 天了,非常感谢你,我再也不会遇到这样的错误了!谢谢
【解决方案2】:

getFieldsTable 是异步的,所以当你调用setStatedataGet 数组将为空。

您可以从getFieldsTable 返回promise 并在所有promise 上使用Promise.all,并在所有promise 都解决后使用数据。

示例

class TablesTree extends Component {
  // ...

  componentDidMount() {
    const promises = this.props.tables.map(name => {
      return this.getFieldsTable(name.TABLE_NAME).then(res => {
        return {
          TABLE_NAME: name.TABLE_NAME,
          columns: res
        };
      });
    });

    Promise.all(promises).then(data => {
      this.setState({ data });
    });
  }

  getFieldsTable(table) {
    return axios
      .get(`table/columns?name=${this.data.user}&psw=${this.data.password}&schema=${this.data.schema}&table=${table}`)
      .then(response => {
        return response.data;
      })
      .catch(error => {
        console.log(error);
      });
  }

  // ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-23
    • 2017-04-04
    • 2019-10-07
    • 2021-05-17
    • 2019-04-29
    • 1970-01-01
    相关资源
    最近更新 更多