首页 > 解决方案 > 在 React 中向 URL 添加变量

问题描述

我需要在 URL 中传递城市名称。我已经声明了变量城市,我在 URL 中传递它,但它没有读取变量我尝试了很多方法,但它们不起作用。

   const Weather=({city})=>{
  const [weather,setWeather]=useState('')
    useEffect(() => {
  
    axios
      .get(`http://api.weatherstack.com/current?access_key=58hgf1d8d36bf336f347d6cc9fbc7&query=${city}`)
      .then(response => {
        setWeather(response.data) 
      })
  }, []) 
// ...

标签: javascriptreactjsreact-native

解决方案


您使用的模板文字语法不正确。你需要:

.get(`http://api.weatherstack.com/current?access_key=Your_access_Key&query=${city}`)

但看起来您在此请求中缺少访问密钥。


推荐阅读