从 api 获取数据并显示在渲染方法上

fetching data from api and shows on Render Method

我从 api 获取数据,但问题是 当我在渲染方法中显示数据时,它显示 "Undefine" 请帮助我修复它

这是我的代码:-

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/>
)}

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

尝试这种方式,如果你有关于它如何工作的问题让我知道。

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/>
    );
  }

我会尝试在您的代码中进行排序。 在 render 方法中获取数据不是一个好主意,最好使用生命周期方法,比如 componentDidMount。为了处理您的请求结果,设置一个状态字段并在您的渲染中从该字段读取数据。所以:

export default class ApiProduct extends Component {
  constructor(){
    super();
    this.state = {
      productData: undefined;
    };
  }     

  async componentDidMount(){
    await this.fetchProduct();
  }

  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) =>{
      this.setState({
        productData: res
      })
    })     
  }

render() {
  const {productData} = this.state;
  console.log(productData);
  return (
    <View/> // add here your code to render data properly
  )
}}

这是一个快速的 Expo 示例,应该向您展示如何呈现一个简单的列表。在 render 方法中调用 fetch 不是一个好主意,因为每次重新渲染都会调用 fetch。

这是世博会小吃https://snack.expo.io/S1-LKIyQE

import React from 'react';
import { Text, View, StyleSheet, FlatList, SafeAreaView } from 'react-native';

export default class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      productData: []
    }
  }

  async componentDidMount () {
    await this.getData();
  }

  async getData() {
    try {
      let url ='https://drawtopic.in/projects/wordpress/wp-json/wc/v2/products?consumer_key=ck_044491712632ef889ec13c75daff5879a8291674&consumer_secret=cs_a8e16c732e1812017e15d278e1dce2765a88c49b'
      let response = await fetch(url, { method:'GET' });
      let responseJson = await response.json();
      this.setState({productData: responseJson});
    } catch (err) {
      console.warn(err);
    }
  }

  renderItem = ({item}) => {
      return (
      <View style={styles.mainItem}>
        <Text>{item.name}</Text>
      </View>
      );
    }

  keyExtractor = (item, index) => {
    return index.toString();
  }


  render() {
    return (
      <SafeAreaView style={styles.container}>
      <FlatList
        extraData={this.state}
        data={this.state.productData}
        keyExtractor={this.keyExtractor}
        renderItem={this.renderItem}
      />
      </SafeAreaView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'white'
  },
  mainItem: {
    width:200,
    height: 80, 
    justifyContent: 'center', 
    alignItems: 'center', 
    margin: 10, 
    backgroundColor: 'yellow',
    borderColor: 'black',
    borderWidth: 1
  },
});

这里我使用了async/await,因为它可以使代码更清晰。这是一篇关于 promisesasync/await https://medium.com/@bluepnume/learn-about-promises-before-you-start-using-async-await-eb148164a9c8.

之间差异的好文章

我还为您提供了一个关于如何使用 FlatList 显示数据的快速示例。您应该查看有关如何正确使用它的文档 https://facebook.github.io/react-native/docs/flatlist

如果您想编辑每个项目在屏幕上的显示方式,则需要更新 renderItem 方法。