React组件未按预期呈现结果

我有一个ReactComponent,它查询rest API,并将其结果呈现为HTML表。结果是以下形式的JSON:

{
  timestamp: ",message: "",requestId: "",responseData: []
}

下面给出了ResultTable react组件,并且期望呈现responseData这是一个列表。这是我看到的问题:

TypeError:无法读取未定义的属性“ map”

因此,看起来好像没有及时从REST API中获取数据以进行渲染。我怎样才能解决这个问题。请在下面找到该组件的代码。提前致谢。

import React,{ Component } from "react";
import axios from "axios";

export class ResultTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      fetchedJson: [],fooBar: false
    };
  }

  handleSubmit(selectedRecipes) {
    if (!this.state.fooBar) {
      let url =
        "http://localhost:8080/ingredients/?recipes=" +
        selectedRecipes.join(",");
      console.log(url);
      axios.get(url).then(res => {
        this.setState({
          fetchedJson: res.data,fooBar: true
        });
      });
    }
  }

  render() {
    this.handleSubmit(this.props.recipelist);
    return (
      <div>
        <h1 align="center">Ingredients</h1>
        <table border="1" align="center">
          <tbody>
            {this.state.fetchedJson.responseData.map(function(ingredient,ingredientIndex) {
              return (
                <tr key={ingredientIndex}>
                  <td>{ingredient.name}</td>
                  <td>{ingredient.amount}</td>
                  <td>{ingredient.unit}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    );
  }
}
chenhongyi2009 回答:React组件未按预期呈现结果

请勿在{{1​​}}函数内部产生副作用。为此,您必须使用lifecycle methods(或对于功能组件使用hooks)。

另外,render是一个异步函数,因此在代码中,您对服务器进行了API调用,并尝试通过axios.get进行映射,直到收到响应为止。在这种情况下,this.state.fetchedJson.responseData是一个空对象,因此fetchedJsonfetchedJson.responseData

此代码应正常工作:

undefined
本文链接:https://www.f2er.com/2786293.html

大家都在问