首页 > 解决方案 > 从 api 获取数据并在 Render Method 上显示

问题描述

我从 api 获取数据,但问题是当我在渲染方法中显示数据时,它显示“未定义”请帮我修复它

这是我的代码:-

var ProductData=''
export default class ApiProduct extends Component {
FetchProduct=()=>{

    fetch('https://drawtopic.in/projects/wordpress/wp- json/wc/v2/products?consumer_key=ck_044491712632ef889ec13c75daff5879a8291674&consumer_secret=cs_a8e16c732e1812017e15d278e1dce2765a88c49b',{
  method:'GET',
})
.then((response) => response.json())
.then((res) =>{
ProductData= res;
})     
}

render() {
{this.FetchProduct()}
{console.warn(ProductData)}
return (
  <View/>
)}

我想在渲染方法中显示所有数据

标签: restreact-nativewoocommercefetch-api

解决方案


试试这种方式,如果您对它的工作原理有疑问,我会知道。

let self;
export default class ApiProduct extends Component {
  constructor(){
    super();
    self = this;
    this.state = {
      productData: null;
    };
  }
  FetchProduct=()=>{
    fetch('https://drawtopic.in/projects/wordpress/wp- json/wc/v2/products?consumer_key=ck_044491712632ef889ec13c75daff5879a8291674&consumer_secret=cs_a8e16c732e1812017e15d278e1dce2765a88c49b',{
      method:'GET',
    })
    .then((response) => response.json())
    .then((res) =>{
      self.setState({ productData: res});
    });
  }

  render() {
    this.FetchProduct();
    console.warn(self.state.productData);
    return (
      <View/>
    );
  }

推荐阅读