You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native与Flask交互报错:saveData不存在的解决方案咨询

React Native 集成 Flask 数据交互问题解决方案

核心错误修复:saveData 未定义问题

你遇到的 ReferenceError: Property 'saveData' doesn't exist 是因为 saveData 函数定义在 useEffect 内部作用域中,外部的 TouchableOpacity 无法访问到它。

修复方案:将 saveData 函数移到 useEffect 外部,作为组件顶层函数:

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

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

  // 移至组件顶层的saveData函数
  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 }),
      });

      if (response.ok) {
        const result = await response.json();
        console.log('数据提交成功:', result);
        setData(result);
      } else {
        console.error('服务器请求错误:', response.statusText);
      }
    } catch (error) {
      console.error('请求异常:', error);
    }
  };

  // 若不需要组件挂载时自动提交数据,可移除原useEffect的自动调用
  // useEffect(() => {
  //   saveData();
  // }, []);

  return (
    // 原有JSX代码保持不变,TouchableOpacity的onPress仍绑定saveData
    <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={String(Sl)}
              onChangeText={text => setSl(Number(text) || 0)}
              keyboardType="numeric"
            />
          </View>
          <View className="rounded-2xl bg-gray-200 p-1 h-30 m-3">
            <TextInput
              placeholder="Sepal width"
              value={String(Sw)}
              onChangeText={text => setSw(Number(text) || 0)}
              keyboardType="numeric"
            />
          </View>
          <View className="rounded-2xl bg-gray-200 p-1 h-30 m-3">
            <TextInput
              placeholder="Petal length"
              value={String(Pl)}
              onChangeText={text => setPl(Number(text) || 0)}
              keyboardType="numeric"
            />
          </View>
          <View className="rounded-2xl bg-gray-200 p-1 h-30 m-3">
            <TextInput
              placeholder="Petal width"
              value={String(Pw)}
              onChangeText={text => setPw(Number(text) || 0)}
              keyboardType="numeric"
            />
          </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 ? data.prediction : '等待提交'}
          </Text>
        </View>
      </View>
    </SafeAreaView>
  );
}

React Native 额外优化点

  1. 输入类型转换:TextInput 的 onChangeText 返回字符串,需转为数字避免传递无效数据给后端,同时设置数字键盘提升体验
  2. 空值安全访问:data 初始为 null,直接访问 data.prediction 会触发报错,添加空值判断

Flask 后端修复与优化

你的 Flask 代码存在多处逻辑错误,无法正确处理前端请求:

import numpy as np
from flask import Flask, request, jsonify
import pickle
from flask_cors import CORS

flask_app = Flask(__name__)
CORS(flask_app)  # 启用跨域支持,否则React Native会触发跨域错误
model = pickle.load(open("model.pkl", "rb"))

@flask_app.route("/predict", methods=["POST"])
def predict():
    # 正确获取前端传递的JSON参数,设置默认值避免空值报错
    sl = request.json.get('Sl', 0)
    sw = request.json.get('Sw', 0)
    pl = request.json.get('Pl', 0)
    pw = request.json.get('Pw', 0)
    
    # 修正特征数组格式,匹配模型输入要求
    features = np.array([[sl, sw, pl, pw]])
    # 取预测结果的第一个值,并转为Python原生类型避免JSON序列化失败
    prediction = model.predict(features)[0]
    prediction_result = int(prediction) if isinstance(prediction, np.generic) else prediction
    
    return jsonify({"prediction": prediction_result})

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

后端关键修复说明

  1. 启用 CORS:必须初始化 CORS,否则前端跨域请求会被浏览器拦截
  2. 正确获取参数:request.json 是属性而非方法,不能加 (),需通过键名提取对应参数
  3. 数据格式兼容:将模型返回的 numpy 类型转为 Python 原生类型,避免 JSON 序列化失败
  4. 限定请求方法:数据提交使用 POST 即可,移除不必要的 GET 方法支持(如需支持可添加分支逻辑)

验证流程

  1. 启动 Flask 后端:确保 model.pkl 文件存在,运行 python app.py
  2. 启动 React Native 项目:真机测试时需将 urlBase 改为电脑局域网 IP(如 http://192.168.x.x:5000),不能使用 127.0.0.1
  3. 输入数据后点击按钮,查看控制台日志和页面结果

内容的提问来源于stack exchange,提问作者Afiq Aiman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 02:44:55