恰好在设置状态完成后调用函数

时间:2021-06-21 17:45:12

标签: reactjs react-hooks

我想每次调用getWeather时都调用函数setLocation()。我该如何实现?

useEffect(() => {
fetch(`${IP_API_URL}`)
.then((res)=> res.json()
.then((data)=>{
  setLocation(data.country.name)
})
)
return getWeather(location)
})

1 个答案:

答案 0 :(得分:1)

setLocation 会有一个 state right ???

const [location, setLocation] = useState();

useEffect(() => {
  fetch(`${IP_API_URL}`)
    .then((res) => res.json()
    .then((data) => {
      setLocation(data.country.name)
    })
  )
}, [])

//add another effect
useEffect(() => { 
  getWeather(location)
}, [location])