使用 React 傳遞數據
P粉696891871
P粉696891871 2023-09-14 20:43:08
0
1
539

在「CameraPage.tsx」下面的程式碼中,做了一個邏輯,其功能是搜尋相機圖像,很簡單,只是發出一個GET 請求,搜尋後端註冊的圖像,稍後會介紹前端顯示,操作正確。

當使用者點擊「InfoOutlineIcon」時,應載入另一個頁面,顯示圖像,但按一下它時,會開啟另一個頁面,但不顯示圖像。出現的問題是,當您單擊時,console.log 顯示圖像已加載,但是當打開新頁面時,好像一切都從頭開始,並且沒有發出任何請求,因此沒有圖像加載/顯示在前端。

// CameraPage.tsx FILE CODE
function CameraPage() {
  const fetchCameraImage = async (cameraId: number, currentPageImages: number): Promise<boolean> => {
    if (!accessToken) {
      console.log("Access token not found");
      return false;
    }

    try {
      console.log("Calling responseFetchCameraImage");
      let responseFetchCameraImage;
      const page = currentPageImages > 0 ? currentPageImages : 1;
      const size = 20;

      responseFetchCameraImage = await axios.get(`${API_URL}/api/v1/imagens/pagination/${cameraId}?page=${page}&size=${size}`, {
        headers: {
          Authorization: `Bearer ${accessToken}`
        },
      });

      console.log(responseFetchCameraImage)
      if (responseFetchCameraImage.status === 200) {
        const images = responseFetchCameraImage.data.items;
        const cameraImages = images.filter((image: any) => image.camera_id === cameraId);
        console.log(cameraImages)

        if (cameraImages && cameraImages.length > 0) {
          const uniqueImagesData: ImageData[] = [];
          cameraImages.forEach((image: any) => {
            const imageData: ImageData = {
              imageURL: `data:image/jpg;base64,${image.image}`,
              data: image.data,
              placa: image.placa,
              score: image.score,
            };
            uniqueImagesData.push(imageData);
          });

          setImageData(uniqueImagesData);

          console.log("Images found");
          return true;
        } else {
          console.error("This camera has no images yet");
          return false;
        }
      } else {
        console.error("Error while trying to fetch camera images");
        return false;
      }
    } catch (error) {
      console.error("Error while trying to fetch camera images");
      errorTimeout = setTimeout(() => {
        setError("");
      }, 3000);
      return false;
    }
  };

  useEffect(() => {
    const fetchData = async () => {
      if (editingCameraId !== null) {
        const success = await fetchCameraImage(editingCameraId, currentPageImages);

        if (success) {
          setCurrentPageImages(1);
          setImageCounter(0);
        }
      }
    };

    fetchData();
  }, [editingCameraId, currentPageImages]);

  return (
    <Layout>
      <Flex justifyContent='center' alignItems='center'>
        <IconButton
          aria-label="View images"
          size="sm">
            <InfoOutlineIcon
              onClick={async () => {
              const hasImage = await fetchCameraImage(camera.id, currentPageImages);
              if (hasImage) {
              routerAfterClickInfoCamera.push('CameraImages')
              }
            }}
          />
        </IconButton>
      {camera.name}
    </Flex>
</Layout>
  );
}

export default CameraPage;

「CameraForm.tsx」下面的程式碼是應顯示圖像的位置,使用routerAfterClickInfoCamera.push('CameraForm') 您將被帶到該頁面,但是,沒有顯示任何內容,如下所示之前說過。但我不明白該怎麼做,我一直在研究但我不明白,如果有人可以幫助我,我很感激。

// CameraForm.tsx FILE CODE
export interface ImageData {
  imageURL: string;
  data: string;
  placa: string;
  score: number;
}

interface CameraModalProps {
  imageData?: ImageData[];
  currentPageImages: number;
  imagesPerPage: number;
}

const CameraImages: React.FC<CameraModalProps> = ({
  imageData = [],
  currentPageImages,
  imagesPerPage,
}) => {

  const [searchPlaca, setSearchPlaca] = useState("");

  const startIndex = (currentPageImages - 1) * imagesPerPage;

  const endIndex = startIndex + imagesPerPage;

  // Filter images by placa
  const filterImagesByPlaca = () => {
    if (searchPlaca === "") {
      return imageData;
    }

    return imageData.filter((image) =>
      image.placa.toLowerCase().includes(searchPlaca.toLowerCase())
    );
  };

  // Get images filtered by placa
  const filteredImages = filterImagesByPlaca();

  const visibleImages = filteredImages.slice(startIndex, endIndex) ?? [];

  return (
    <Layout>
      <Head title={"Câmeras"} />
      <Flex justifyContent="space-between">
        <Title title="IMAGEM" />
      </Flex>

      <Box>
        <Input
          type="text"
          border="none"
          style={{
            marginLeft: "1rem",
            outline: "none",
            backgroundColor: "transparent",
            borderBottom: "1px solid #ccc",
          }}
          width="auto"
          placeholder="Buscar placa"
          value={searchPlaca}
          onChange={(e) => setSearchPlaca(e.target.value)}
        />
      </Box>
      <Box>
        {visibleImages.map((imageData, index) => {
          const { imageURL, data, placa, score } = imageData;
          const imageNumber = startIndex + index + 1;
          return (
            <Box key={index} borderBottom="1px solid #ccc" py={2}>
              <Text fontSize={["sm", "md"]} fontWeight="normal">
                Imagem {imageNumber}
              </Text>
              <Text fontSize={["sm", "md"]} fontWeight="normal">
                Data: {data}
              </Text>
              <Text fontSize={["sm", "md"]} fontWeight="normal">
                Placa: {placa}
              </Text>
              <Text fontSize={["sm", "md"]} fontWeight="normal">
                Score: {score}
              </Text>
              <ChakraImage src={imageURL} alt={`Image ${index}`} />
            </Box>
          );
        })}
      </Box>
    </Layout>
  )
}

export default CameraImages;

P粉696891871
P粉696891871

全部回覆(1)
P粉464113078

我認為問題是您正在呼叫“CameraImages”元件,但您沒有發送道具。這就是圖像不顯示的原因。

你應該做這樣的事情。

<CameraImages imageData={imageData} currentPageImages={currentPageImages} imagesPerPage={imagesPerPage} />
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板