【问题标题】:Expo : How can I fetch data from Django Rest Framework API?Expo:如何从 Django Rest Framework API 获取数据?
【发布时间】:2022-01-24 16:13:14
【问题描述】:

我正在使用 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-native django-rest-framework fetch expo


【解决方案1】:

您应该在功能组件中使用 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' 作为样式

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    • 2018-11-10
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多