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

React Native调用predictBodyFat报错x must be a number or array怎么解决

问题原因
  • 核心类型错误:React Native的TextInput组件onChangeText回调返回的输入值始终是字符串类型,代码直接将字符串存入waist状态,调用predictBodyFat时传入的是字符串参数。你在onPress中执行了parseFloat(waist)但没有将转换后的数值赋值给变量,实际传入预测函数的还是原始字符串,而ml-regression-simple-linear的predict方法要求入参必须是数字或数组,因此抛出对应错误。
  • 潜在路径错误:你的逻辑文件名为prediction-controller.js,但代码中require的路径是./BodyfatPrediction/controller/predictionController,文件名拼写不一致会导致模块加载失败。
解决方案
  1. 修正类型转换逻辑,确保传入预测函数的是数字类型,两种修改方式可选:
    • 方式1:输入变更时直接存储数值
      修改TextInput的onChangeText回调:
    onChangeText={(waistStr) => {
      setWaist(parseFloat(waistStr) || 0.0);
    }}
    
    • 方式2:点击计算时转换后再传入
      修改TouchableOpacity的onPress回调:
    onPress={() => {
      const waistNum = parseFloat(waist) || 0.0;
      setBodyfat(predictBodyFat(waistNum));
    }}
    
  2. 修正导入路径,确保和实际文件名一致:
const predictBodyFat = require("./BodyfatPrediction/controller/prediction-controller");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:06:07