你好我有反应的问题,我想从api得到结果并显示信息,但我得到一个错误, error map undeff任何人都可以提供帮助吗? 连接很好,但我无法映射结果
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {info: []};
}
componentDidMount() {
this.FlightList();
}
FlightList() {
$.getJSON('api')
.then(({ results }) => this.setState({ info: results }));
}
render() {
let infos = this.state.info.map((item) => (
<div>
<h1>{item.flight.name}</h1>
</div>
));
return (
<div id="layout-content" className="layout-content-wrapper">
<div className="panel-list">{ infos }</div>
</div>
);
}
}
&#13;
答案 0 :(得分:0)
您正在尝试在api请求完成之前访问数据并且设置状态是因为组件在componentDidMount被触发之前呈现一次,这就是为什么当您尝试映射状态时它会抛出错误为空。 要解决此问题,您需要等待数据,例如通过维持
等加载状态export default class Home extends Component {
constructor(props) {
super(props);
this.state = {info: [],isLoading:true};
}
componentDidMount() {
this.FlightList();
}
FlightList() {
$.getJSON('api')
.then(({ results }) => this.setState({ info: results,isLoading:false }));
}
render() {
let infos=[]
if(isLoading) return <div>Loading data....</div>
if(!isLoading){
{infos = this.state.info.map((item) => (
<div>
<h1>{item.flight.name}</h1>
</div>
))};
return (
<div id="layout-content" className="layout-content-wrapper">
<div className="panel-list">{ infos }</div>
</div>
);
}
}
答案 1 :(得分:0)
您可以尝试在构造函数中绑定FlightList。 在构造函数中:
constructor(props) { super(props); this.state = {info: []}; this.FlightList = this.FlightList.bind(this);}
答案 2 :(得分:0)
您需要定义默认状态,如
state = {info:[]}
因此,当您尝试映射时,它不会打印错误,因为我们已经为状态中的信息定义了默认值。