【问题标题】:Passing props to an axios query将 props 传递给 axios 查询
【发布时间】:2021-06-14 10:12:33
【问题描述】:

我的意图是获取所选国家的天气数据,将 selectedCountry.capital 传递给查询,因此在显示国家数据时会显示当前国家首都的天气。

useEffect(() => {

  axios
    .get(
      `http://api.weatherstack.com/current?access_key=b51dfd70b0b2ccf136a0d7352876661c&query=${selectedCountry.capital}`
    )
    .then(res =>{
      console.log(res.data)
      console.log("capital"+selectedCountry.capital)
      setWeather(res.data.current)
    } )

}, [])

第一个问题:我没有将 selectedCountry.capital 传递给查询,因为 console.log("capital"+selectedCountry.capital) 返回未定义。

如果我对查询进行硬编码,我会收到天气响应。

useEffect(() => {

  axios
    .get(
      `http://api.weatherstack.com/current?access_key=b51dfd70b0b2ccf136a0d7352876661c&query=New York`
    )
    .then(res =>{
      console.log(res.data)
      console.log("capital"+selectedCountry.capital)
      setWeather(res.data.current)
    } )

}, [])

如何将 selectedCountry.capital 传递给天气查询?

完整代码: code sandbox

import React, { useState, useEffect } from 'react'
import axios from 'axios'
//setCountries is a function for setting the country's state
const App = () => {
  const [countries, setCountries] = useState([])
//Filter
const [searchFilter, setSearchFilter] = useState('')

//Update state with button
const [selectedCountry, setSelectedCountry] = useState('')

const [weather, setWeather] = useState('')
  
const hook = () => {
    console.log('effect')
    axios
      .get('https://restcountries.eu/rest/v2/all')
      .then(response => {
        console.log('promise fulfilled')
        setCountries(response.data)
        
      })
  }

  useEffect(hook,[])
/*   by default the effect is always run after the component has been rendered. In our case, however, we only want to execute the effect along with the first render.
  The second parameter of useEffect is used to specify how often the effect is run. If the second parameter is an empty array [], then the effect is only run along with the first render of the component. */

  console.log('render', countries.length, 'countries')
  console.log(countries)

/* weather */
useEffect(() => {

  axios
    .get(
      `http://api.weatherstack.com/current?access_key=b51dfd70b0b2ccf136a0d7352876661c&query=New York`
    )
    .then(res =>{
      console.log(res.data)
      console.log("capital"+selectedCountry.capital)
      setWeather(res.data.current)
    } )

}, [])



  //When button es clicked the state is set, and the state variable is used

  const renderCountryDetails = () => {
    return (
      selectedCountry && (
        <p key={selectedCountry.alpha2Code}>
       <p>   Capital: {selectedCountry.capital}.</p>
       <p>  Population:{" "}
          {selectedCountry.population}</p> 

          <p>
            <img src={selectedCountry.flag} style={{ width: '200px'}}/>
</p> 
        
<h3>Languages</h3>
<p>      {selectedCountry.languages.map(language => <li key={language.name}>{language.name}</li>)}



</p>



</p>


      )
    );
  };



const filteredCountries =
searchFilter.length === 1
? countries
: countries.filter(
(country) => country.name.toLowerCase().indexOf(searchFilter.toLowerCase()) > -1
)

//showCountries returns either a message or else the contents of filteredcountries array
const showCountries = () => {


if (filteredCountries.length > 10) {
return 'Too many matches, keep on typing'
}


if (filteredCountries.length > 0 
    && filteredCountries.length<10 
    && filteredCountries.length>1 ) 
    {
      return (
        <div>
          {filteredCountries.map((country) => (
            <p key={country.alpha2Code}>
              {country.name}
              {
                //Update stste when button is clicked, passing country as a prop to the state
                //onClick state is updated, causing the page to refresh and executing renderCountryDetails
                //that uses the set state (the country) to render the info.
                <button onClick={
                  () => setSelectedCountry(country)}>
                  show
                </button>
              }
            </p>
          ))}
          <div>{renderCountryDetails()}</div>
          <div>
            <p></p>
        </div>
        </div>
      );
    }
    
    

    if (filteredCountries.length === 1) {
      return filteredCountries.map((country) =>

      
  <p key={country.alpha2Code}>
    <p>Capital: {country.capital}.
    <p> Population: {country.population} </p> 
    <h3>languages</h3>
                {country.languages.map(language => <li key={language.name}>{language.name}</li>)}

    <p><img src={country.flag} style={{ width: '200px'}}/>
    </p> 
    
    </p>
    </p>

  )
      }
    } 
     


const searchHandler = (e) => {
  //setSelectedCountry state is set to empty
  setSelectedCountry("");
setSearchFilter(e.target.value)
}

  return (
<div>

<div>
<h1>Countries</h1>
</div>
<div>
Type to find countries: 
<input onChange={searchHandler} />
<div>
{showCountries()}
</div>
</div>

</div>
  );
}


export default App;

【问题讨论】:

    标签: reactjs axios


    【解决方案1】:

    我认为你对 useEffect 很了解。如果你使用useEffect(()=&gt; {}, []),它将在生命周期组件的第一次重新渲染。

    我只是快速修复以显示您的代码,如下所示:imagecode

    如果将selectCity 状态置于useEffect(()=&gt;{}, [selectCity] 中,当selectCity 发生变化时,组件将重新渲染。

    希望这对你有用。

    【讨论】:

    • 你好。按照你说的做[selectedCountry.capital])我可以记录资本。但这是一种奇怪的方法。而且我无法显示天气数据,因为只有在我选择国家后它才会通过 selectedCountry.capital。应该有另一种方式。
    • 哦。我有你的问题。 Ypu 只能通过一些动作设置selectedContry.capital 的值一次,例如单击“确定”按钮然后设置值`capital'。
    • 你也可以在useEffect函数if (!selectedContry.capital) return;中查看。在具有有效值后,只会显示一次国家/地区。
    猜你喜欢
    • 2021-08-30
    • 2020-12-04
    • 2018-10-24
    • 2021-01-28
    • 2019-08-11
    • 2019-03-18
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多