【发布时间】:2021-03-08 09:48:00
【问题描述】:
我已尝试访问 WP REST 以进行 React。 Fetch 方法获取我已经安慰和检查的数据。当我尝试将数据绑定到前端映射函数时会引发错误。
import React,{ Component } from 'react';
class HomePage extends Component{
constructor(props){
super(props);
this.state = {
loading:true,
Companies:[]
}
}
async componentDidMount(){
let data= fetch('https://example.co/wp-json/wp/v2/company?per_page=10').then((resp) =>{
resp.json().then((res)=>{
console.log(res);
this.setState({Companies:res,loading:false})
})
})
}
render() {
const Companies = this.state.Companies;
return (
<div>
<section className="selected-firms-banner" style={{backgroundImage: 'url("https://example.co/wp-content/themes/demotheme/images/Hero-Banner.jpg")'}}>
<div className="container">
<div className="banner-content">
<div className="row">
<div className="col-md-12 banner-title">
<h1> Firms Premised on Top to Bottom Scrutiny and Analysis</h1>
</div>
<div className="col-md-12 banner-description">
<p>Discover the top-notch Software Development firms over the globe. We investigate every possibility to give you a chance to find a portion of the eminent firms that will concur your needs and conveys superb administrations/surveillance.</p>
</div>
</div>
</div>
</div>
</section>
<section className="sf-post-listing">
<div className="container">
<div className="listing-post-main">
<div className="row">
{Companies.map((company, i) => {
return (<div className="col-md-6 col-lg-4 col-sm-12">
<div className="listing-post-card effect-image-1 zoom-effect-1">
<img src="images/listing1.jpg" className="img-fluid" />
<div className="overlay simple-overlay"><i className="fa fa-link" aria-hidden="true" /></div>
</div>
<h3>{company.title}</h3>
</div> )
})}
</div>
</div>
</div>
</section>
</div>
);
}
}
export default HomePage;
完整的组件是正确的,只是渲染数据部分会导致问题。
错误:对象作为 React 子对象无效(找到:带键的对象 {渲染})。如果您打算渲染一组孩子,请使用 代替数组。
【问题讨论】:
-
你需要等待api然后调用它