如何在React Native中向Flask发送并获取值

0 投票
1 回答
31 浏览
提问于 2025-04-14 16:42

我正在做一个简单的项目,想把 React Native 和 Flask 整合在一起,但因为知识和资料不足,搞不太懂怎么实现这个。现在遇到的错误是:

错误:ReferenceError: 属性 'saveData' 不存在

请问有什么好的解决办法吗?

App.Js

import React, { Component, useEffect, useState } from 'react';
import { Text, View, SafeAreaView, TextInput, TouchableOpacity } from 'react-native';

export default function Homescreen() {
  const urlBase = 'http://127.0.0.1:5000'; // Corrected variable name

  const [data, setData] = useState();
  const [Sl, setSl] = useState(0);
  const [Sw, setSw] = useState(0);
  const [Pl, setPl] = useState(0);
  const [Pw, setPw] = useState(0);

  useEffect(() => {
    const saveData = async () => {
      const url = `${urlBase}/predict`;

      try {
        const response = await fetch(url, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ Sl, Sw, Pl, Pw }), // Pass an object with properties
        });

        if (response.ok) {
          const result = await response.json();
          console.log('Data is added successfully:', result);
          setData(result);
        } else {
          console.error('Error fetching data from the server:', response.statusText);
        }
      } catch (error) {
        console.error('Error:', error);
      }
    };

    saveData(); // Call the function
  }, []); // Empty dependency array means this effect runs once on component mount

  return (
    <SafeAreaView className="flex-1 p-5 bg-white ">
      <View className=" flex-col">
        <View>
          <Text className="font-bold text-sky-700 text-center text-2xl">
            Beta Sypnapse Ai Project
          </Text>
        </View>
        <View className="m-3">
          <View className="rounded-2xl bg-gray-200 p-1 h-30 m-3">
            <TextInput
              placeholder="Sepal length"
              value={Sl}
              onChangeText={text => setSl(text)}
            />
          </View>
          <View className="rounded-2xl bg-gray-200 p-1 h-30 m-3">
            <TextInput
              placeholder="Sepal width"
              value={Sw}
              onChangeText={text => setSw(text)}
            />
          </View>
          <View className="rounded-2xl bg-gray-200 p-1 h-30 m-3">
            <TextInput
              placeholder="Petal length"
              value={Pl}
              onChangeText={text => setPl(text)}
            />
          </View>
          <View className="rounded-2xl bg-gray-200 p-1 h-30 m-3">
            <TextInput
              placeholder="Petal width"
              value={Pw}
              onChangeText={text => setPw(text)}
            />
          </View>
          <TouchableOpacity onPress={saveData}>
            <View className="rounded-2xl bg-blue-400 w-48 h-12 self-center items-center p-3 m-3">
              <Text className=" text-slate-50 text-sm">Identify the data</Text>
            </View>
          </TouchableOpacity>
        </View>
        <View>
          <Text className="self-center">
            The result will be : {data.prediction}
          </Text>
        </View>
      </View>
    </SafeAreaView>
  );
}

app.py

import numpy as np
from flask import Flask, request, jsonify, render_template
import pickle
from urllib.parse import quote as url_quote
from flask_cors import CORS

# Create flask app
flask_app = Flask(__name__)
model = pickle.load(open("model.pkl", "rb"))


@flask_app.route("/predict", methods=["POST", "GET"])
def predict():
    sl = request.json()
    sw = request.json()
    pl = request.json()
    pw = request.json()
    features = [np.array([sl, sw, pl, pw])]
    prediction = model.predict(features)
    return {"prediction": prediction}


if __name__ == "__main__":
    flask_app.run(debug=True)

目的是能够从 React 和 Python 之间发送和获取数据

1 个回答

0

你在useEffect里面声明了saveData()这个函数,这就意味着这个函数只能在这个函数的范围内使用。我看到你在第76行把这个函数当作参数传递:

      <TouchableOpacity onPress={saveData}>
        <View className="rounded-2xl bg-blue-400 w-48 h-12 self-center items-center p-3 m-3">
          <Text className=" text-slate-50 text-sm">Identify the data</Text>
        </View>
      </TouchableOpacity>

所以你会遇到一个引用错误。如果你想把这个函数传递给这个组件,应该在组件内部声明这个函数,而不是放在useEffect里面。

撰写回答