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

React Native中API请求模板字面量未解析,仅作字符串生效的原因咨询

模板字面量在React Native API请求中未解析的问题解决

我一眼就揪出问题所在啦!你遇到的模板字面量没被解析的情况,核心原因非常简单——字符串的包裹符号用错了。

问题根源

JavaScript里的模板字面量(也就是带${变量}的插值语法),必须用**反引号()**来包裹整个字符串才行。而你在fetch请求里用的是双引号("),双引号/单引号包裹的是普通字符串,会直接把${fname}和${sname}`当成纯文本发送给API,自然没法替换成你输入的名字参数。

你的代码问题点

看这段关键代码:

fetch("https://love-calculator.p.rapidapi.com/getPercentage?fname=${fname}&sname=${sname}", {
  // ...其他配置
})

就是这里的双引号,直接导致模板语法失效,参数完全没被替换。

修复方案

只需要把URL的双引号换成反引号就能解决核心问题,同时我还帮你优化了几个细节(比如给TextInput绑定value,确保输入和状态同步,新增错误处理):

import React, { useState } from 'react';
import { View, StyleSheet, Text, TextInput, Button } from 'react-native';
import DisplayPer from './DisplayPer';

const Body = () => {
  const [fname, setFname] = useState("")
  const [sname, setSname] = useState("")
  
  const calculate = () => {
    // 把双引号换成反引号,模板字面量就能正常解析了
    fetch(`https://love-calculator.p.rapidapi.com/getPercentage?fname=${fname}&sname=${sname}`, {
      method: "GET",
      headers: {
        "x-rapidapi-key": "00298dcae5mshba42f70f49fc1b6p148d95jsn941e18e734e5",
        "x-rapidapi-host": "love-calculator.p.rapidapi.com"
      }
    })
    .then(response => {
      // 新增请求状态判断,处理HTTP错误
      if (!response.ok) throw new Error(`请求失败:${response.status}`);
      return response.json();
    })
    .then(result => {
      console.log(result);
      // 这里可以把结果传递给DisplayPer组件,比如:
      // setResult(result); 然后通过props传给DisplayPer
    })
    .catch(error => {
      console.error('请求出错:', error);
    });
  };

  return(
    <View style={styles.bodycontainer}>
      <Text style={styles.bodytext}>Enter Names</Text>
      <TextInput 
        style={styles.bodyinput} 
        placeholder="First name" 
        onChangeText={setFname} 
        value={fname} // 绑定value,确保输入和状态同步
      />
      <TextInput 
        style={styles.bodyinput} 
        placeholder="Second name" 
        onChangeText={setSname} 
        value={sname} // 同样绑定value
      />
      <Button 
        onPress={calculate} 
        title="Calculate Love Percentage" 
        color="#841584" 
        accessibilityLabel="Calculate love percentage between two names" 
      />
      <DisplayPer />
    </View>
  );
};

export default Body;

额外小提示

  • 变量名建议用小驼峰命名(比如setFname而非setfname),这是JavaScript通用规范,代码可读性更高。
  • 记得给fetch加上错误捕获(.catch()),避免请求失败时没有任何反馈。
  • 如果要把计算结果展示在DisplayPer里,可以通过状态+props传递,比如先声明const [result, setResult] = useState(null),然后在.then里调用setResult(result),最后渲染<DisplayPer result={result} />。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 20:33:02