我有一个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>
);
}
}