【问题标题】:Fetching data in React Native app using API使用 API 在 React Native 应用程序中获取数据
【发布时间】:2021-04-09 01:17:51
【问题描述】:

我正在 React Native 上开发一个应用程序,我想通过这个应用程序连接我在 Python (NLP) 上开发的聊天机器人。如何从我的 python 训练模型中获取数据并使用 React Native 前端实时运行它

【问题讨论】:

    标签: python json react-native flask django-rest-framework


    【解决方案1】:
    import React, { useEffect, useState } from 'react';
    import { ActivityIndicator, FlatList, Text, View } from 'react-native';
    
    export default App = () => {
      const [isLoading, setLoading] = useState(true);
      const [data, setData] = useState([]);
    
      useEffect(() => {
        fetch('https://reactnative.dev/movies.json')
          .then((response) => response.json())
          .then((json) => console.log(json))
          .catch((error) => console.error(error))
          .finally(() => setLoading(false));
      }, []);
    
      return (
        <View style={{ flex: 1, padding: 24 }}>
          {isLoading ? <ActivityIndicator/> : (
            <FlatList
              data={data}
              keyExtractor={({ id }, index) => id}
              renderItem={({ item }) => (
                <Text>{item.title}, {item.releaseYear}</Text>
              )}
            />
          )}
        </View>
      );
    };
    

    上面的例子展示了如何在反应原生应用中获取数据。 将 URL https://reactnative.dev/movies.json 替换为您的 API url。

    【讨论】:

      【解决方案2】:

      试试这样的:

      export default class Hook extends Component {
        state = {
          apiResponse: '',
          isLoading: false
        };
      
        async componentDidMount() {
         this.fetchData()
        }
      
        fetchData = async () => {
           this.setState({isLoading:true})
          const response = await axios("https://reactnative.dev/movies.json");
            this.setState({apiResponse:response.data,isLoading:false})
      
        }
      

      【讨论】:

        【解决方案3】:

        使用 axios [https://github.com/axios/axios]

        你可以很简单地从 api 获取数据

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-11-14
          • 2021-07-19
          • 2021-09-26
          • 1970-01-01
          • 2019-11-27
          • 2017-07-25
          • 1970-01-01
          • 2022-01-17
          相关资源
          最近更新 更多