【问题标题】:React props not loading fast enoughReact 道具加载速度不够快
【发布时间】:2020-07-26 09:24:46
【问题描述】:

我正在尝试使用Effect 在组件加载时设置地图的纬度和经度。问题是组件在 props 添加到 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,
    })
}, [])

【问题讨论】:

    标签: reactjs react-props use-effect


    【解决方案1】:

    将 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 不知道它的环境可以这么说,因为它在组件安装上运行,但它并不关心会发生什么。当你将 props 添加为依赖项时,它不仅会在第一次运行,它还会监视 props 的更改,然后在检测到更改时再次运行。

    【讨论】:

      【解决方案2】:

      解构props并添加依赖到效果:

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

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

      【讨论】:

      • 谢谢!解构与像上面的示例一样将道具放入依赖项中是否有优势?
      • 是的。每当您将 props 放入 deps 数组时,React 都会抱怨。只放最低限度的依赖,以减少运行效果的次数。
      • 太棒了!很简单。我已经搞砸了一个半小时。非常感谢 -
      猜你喜欢
      • 2020-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-16
      • 2012-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多