世博会:如何从 Django Rest Framework API 获取数据?

Expo : How can I fetch data from Django Rest Framework API?

我正在使用 Expo 5.0.1。 我有一个 API 可以正常工作。

这是我的全部 App.js :

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

const [data, setData] = useState([{title: "First title"}]);

  useEffect(() => {
    fetch('http://192.168.1.68:89/cards/', {
      method: "GET"
    })
    .then(resp => resp.json())
    .then(data => {
      console.log(data)
    })
    .catch(error => console.log("Error is : ", error))
  }, [])

const renderData = (item) => {
  return(
    <View style={styles.view}>
      <Text>{item.user}</Text>
      <Text>{item.is_suspended}</Text>
      <Text>{item.id}</Text>
    </View>
  ) 
}

export default function App() {

  return (
    <View style={styles.view}>
      <FlatList
      data = {data}
      renderItem={({item}) => {
        return renderData(item)
      }}
      keyExtractor={item => item.user}
      />      
    </View>
  );
}

const styles = StyleSheet.create({
  Bold: {fontWeight: '600',},
  Red: {color: 'red'}, 
  px30: {fontSize: '20px',},
  view: {justifyContent: 'center', textAlign: 'center', paddingTop: '20px',},
})

我什至无法从我的“.catch”中获取错误。 这是错误: Error1

这是我将 useEffect 代码放入函数应用程序时的情况: Error2

有人可以帮我从 Rest 获取数据 Api?

您应该在功能组件中使用 React 状态挂钩。 这就是你得到那个错误的原因。 请尝试使用此代码。


import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, FlatList } from 'react-native';
export default function App() {

const [data, setData] = useState([{title: "First title"}]);

  useEffect(() => {
    fetch('http://192.168.1.68:89/cards/', {
      method: "GET"
    })
    .then(resp => resp.json())
    .then(data => {
      console.log(data)
    })
    .catch(error => console.log("Error is : ", error))
  }, [])

const renderData = ({item, index}) => {
  return(
    <View style={styles.view}>
      <Text>{item.user}</Text>
      <Text>{item.is_suspended}</Text>
      <Text>{item.id}</Text>
    </View>
  ) 
}

  return (
    <View style={styles.view}>
      <FlatList
      data = {data}
      renderItem={renderData}
      keyExtractor={(i, k) => k.toString()}
      />      
    </View>
  );
}

const styles = StyleSheet.create({
  Bold: {fontWeight: '600',},
  Red: {color: 'red'}, 
  px30: {fontSize: '20px',},
  view: {justifyContent: 'center', textAlign: 'center', paddingTop: '20px',},
})

编辑

我发现你的风格也不对。 将它们替换为

const styles = StyleSheet.create({
  Bold: {fontWeight: 600,},
  Red: {color: 'red'}, 
  px30: {fontSize: 20,},
  view: {justifyContent: 'center', textAlign: 'center', paddingTop: 20,},
})

React native 不接受 'px' 作为样式