开发者问题收集

React TypeError:无法将未定义或空转换为对象

2020-04-21
1482

我正在 React 应用中创建上一个和下一个按钮。我试图获取页面的当前索引(我有一个存储在对象中的页面列表)

代码如下

import React, { useState, useEffect } from "react";

function Preview({ match }) {
  const [imageName, setImageName] = useState(); //IMPORTANT
  const [images, setImages] = useState(); //IMPORTANT

  const [currentIndex, setCurrentIndex] = useState(); //IMPORTANT

  function getIndexByImageName(name) { //IMPORTANT
    Object.keys(images).map((image, index) => {
      if (image === name) return index;
    });
  }

  function importAll(r) {
    let images_ = {};

    r.keys().map((item, index) => {
      images_[item.replace("./", "")] = r(item);
    });

    return images_;
  }

  useEffect(() => {
    //This sets the state.
    setImageName(String(match.params.id));
    setImages(importAll(require.context("../coco-images", false, /\.jpg/)));
  }, []);

  useEffect(() => {
    setCurrentIndex(getIndexByImageName(imageName)); //IMPORTANT (This sets the current index. But returns an error)
  }, []);

  return null;
}

export default Preview;

我收到的错误是“TypeError:无法将未定义或 null 转换为对象”

需要明确的是,imageName 和 images 不为 null 或未定义(因为当我使用 console.log 记录时,它有我需要的数据)。

提前致谢!

2个回答

将默认值分配给图像:

765651715
Taghi Khavari
2020-04-21

我已经修复了它。

我通过创建状态“ finishedLoading ”修复了它,并在 finishedLoading 为真时设置状态

所以这里是完整的代码

import React, { useState, useEffect } from "react";
import loading from "../images/loading.gif";

function Preview({ match }) {
  const [imageName, setImageName] = useState();
  const [images, setImages] = useState();
  const [finishedLoading, setFinishedLoading] = useState(false);
  const [currentIndex, setCurrentIndex] = useState();

  function setCurrent() {
    if (finishedLoading) {
      Object.keys(images).map((image, index) => {
        if (image === imageName) setCurrentIndex(index);
      });
    } else {
      return null;
    }
  }

  function importAll(r) {
    let images_ = {};

    r.keys().map((item, index) => {
      images_[item.replace("./", "")] = r(item);
    });

    setFinishedLoading(true);
    return images_;
  }

  useEffect(() => {
    setImageName(String(match.params.id));
    setImages(importAll(require.context("../coco-images", false, /\.jpg/)));
  }, []);

  useEffect(() => {
    if (finishedLoading) setCurrent(); //I've change getIndexByName to setCurrent
  }, [finishedLoading]);

  return null;
}

export default Preview;
TheBigBro122
2020-04-21