反应道具加载速度不够快



当组件加载时,我正在尝试使用Effect来设置地图的纬度和经度。问题是组件在道具添加到useEffect之前加载并渲染。

useEffect(() => {
console.log(props.bandLocation)
// If I run this with a setTimeout it returns the data... but without the setTimeout it is an empty array. I need to set the latitude and longitude below to the data passed in through props... 
setViewport({
latitude: props.bandLocation[0],
longitude: props.bandLocation[1],
width: '100%',
height: '200px',
zoom: 2,
})
}, [])

取消结构props并添加依赖项以达到效果:

const { bandLocation } = props
useEffect(() => {
setViewport({
latitude: bandLocation[0],
longitude: bandLocation[1],
width: '100%',
height: '200px',
zoom: 2,
})
}, [bandLocation])

这样,只有当bandLocation发生变化时,效果才会运行。

将useEffect依赖项设置为props,以便在道具更改时相应地重新渲染组件。像这样:

useEffect(() => {
console.log(props.bandLocation)
// If I run this with a setTimeout it returns the data... but without the setTimeout it is an empty array. I need to set the latitude and longitude below to the data passed in through props... 
setViewport({
latitude: props.bandLocation[0],
longitude: props.bandLocation[1],
width: '100%',
height: '200px',
zoom: 2,
})
}, [props])

为了进一步解释这一点,你目前拥有的useEffect不知道它的周围环境,比如说,它在组件安装上运行,但它不在乎发生了什么。当您将道具添加为依赖项时,它不仅会在第一次运行,还会监视道具的更改,然后在检测到更改时再次运行。

最新更新