当道具依赖项更改时,React useEffect 钩子不会触发

lay*_*thq 2 javascript reactjs react-hooks

我正在使用 useEffect 挂钩根据photos传入的道具中的数据进行 API 调用。

const ImageCarousel = ({ src, photos }) => {
  const [photoList, setPhotos] = useState([]);
  const storageRef = firebase.storage().ref();
  console.log("photos prop:", photos);

  const getImage = photoId => {
    return new Promise((resolve, reject) => {
      storageRef
        .child("images/" + photoId)
        .getDownloadURL()
        .then(url => resolve(url))
        .catch(error => reject(error));
    });
  };

  useEffect(() => {
    console.log("trigger");
    Promise.all(
      photos.map(async photoId => {
        const url = await getImage(photoId);
        return url;
      })
    )
      .then(photoUrls => {
        setPhotos(photoUrls);
      })
      .catch(e => console.log(e));
  }, [photos]);

return (...)
}

Run Code Online (Sandbox Code Playgroud)

我已经将照片道具传递到我的 useEffect 钩子的依赖数组中,所以它应该在照片道具改变时触发。我可以看到 prop 确实在控制台中发生了变化,但是当 prop 发生变化时,我的 useEffect 钩子没有触发。这是出现在我的控制台中的内容:

控制台日志

为什么 useEffect 没有触发两次?根据我的理解,它应该在组件第一次渲染时触发,并在每次photosprop 更改时再次触发。

Nir*_*irG 9

尽量确保你的photos道具是不可变的,这意味着,每次有变化时你都会发送一个新数组,而不是改变数组

  • 感谢您,我现在有足够的声誉来添加评论:) (2认同)