【问题标题】:Const being treated as string React.JS / fetchconst 被视为字符串 React.JS / fetch
【发布时间】:2018-07-01 10:50:19
【问题描述】:

我正在尝试获取表单值并将它们传递给 API 调用,但变量 ${city} 被视为字符串。我已经查看了 fetch 调用中变量使用的各种其他示例,这似乎是正确的。我做错了什么?

功能:

class App extends Component {
  getWeather = async (e) => {
    const api_key = '11deac5d16f942afda257188d880da59';
    e.preventDefault(); 
    const city = e.target.elements.city.value;
    const country = e.target.elements.country.value;

    const call = await fetch('http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=11deac5d16f942afda257188d880da59');
    const data = await call.json();

    console.log(data);
    }

形式:

import React from "react";

class Form extends React.Component {
render() {
return (
    <form onSubmit={this.props.getWeather}>
        <input type="text" name="city" placeholder="City" />
        <input type="text" name="country" placeholder="Country" />
        <button>Fetch Weather</button>   </form>
);
}
};

export default Form;

【问题讨论】:

  • 使用反引号代替单引号(此处转义)`My name is${name}`。还要检查您的fetch call 是否正确
  • @Tico 使用 insomnia 来验证通话。改为反引号并完美运行,谢谢。
  • 哈哈它发生了,很高兴我能帮忙

标签: javascript reactjs fetch


【解决方案1】:

ES6 中的字符串插值应该与反引号一起使用。 ``。

在你的情况下,改变这一行:

const call = await fetch('http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=11deac5d16f942afda257188d880da59');

到

const call = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=11deac5d16f942afda257188d880da59`);

【讨论】:

    【解决方案2】:

    你需要使用反引号

    `http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=11deac5d16f942afda257188d880da59`
    

    vs 你所拥有的:

    'http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=11deac5d16f942afda257188d880da59'
    

    【讨论】:

      猜你喜欢
      • 2014-11-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 2016-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多