Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

Имеется код на react в файле arachnoentomology.tsx import Search from "./Search"; import…

  1. User

    Имеется код на react в файле arachnoentomology.tsx

    import Search from "./Search"; import CustomizedHook from "./Tags"; import Viewer from "./Viewer"; import React, { useEffect, useState } from "react";

    const Arachnoentomology = () => { const [visible, setVisible] = useState(false); // Изначально устанавливаем видимость в false const [visible_hook, setVisible_hook] = useState(false); // Изначально устанавливаем видимость в false const [items, setItems] = useState<Item[]>([]);

    interface Item { id: number; title: string; preview: string; dzi: string; }

    useEffect(() => { fetch("/api/tasks") .then((response) => response.json()) .then((data) => setItems(data)) .catch((error) => console.error(error)); }, []);

    function toggleViewer() { setVisible((prevVisible) => !prevVisible); // Инвертируем значение видимости }

    function toggleFilter() { setVisible_hook((prevVisible) => !prevVisible); // Инвертируем значение видимости }

    return ( Арахноэнтомология Медицинская арахноэнтомология или медицинская энтомология — раздел медицинской паразитологии; наука, изучающая заболевания человека, вызываемые членистоногими или передающиеся ими, морфологию и экологию членистоногих эктопаразитов человека, их взаимодействие с самим человеком, и исследующая возбудителей этих болезней, а также меры борьбы с ними и профилактики. Расширенный поиск {visible_hook && } {items.map((item, index) => { console.log(item.preview); console.log(item.dzi); console.log(item.title); return ( {item.title} ); })} Viewer_window {visible && } {/* Рендерим Viewer, если visible === true */} ); };

    export default Arachnoentomology;

    а так же скрипт openseadragon

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

    const OpenSeaDragonViewer = ({ image }) => { const [viewer, setViewer] = useState( null);

    useEffect(() => { if (image && viewer) { viewer.open(image.source); } }, [image]);

    const InitOpenseadragon = () => { viewer && viewer.destroy(); setViewer( OpenSeaDragon({ id: "openSeaDragon", prefixUrl: "openseadragon-images/", animationTime: 0.5, blendTime: 0.1, constrainDuringPan: true, maxZoomPixelRatio: 2, minZoomLevel: 1, visibilityRatio: 1, zoomPerScroll: 2 }) ); };

    useEffect(() => { InitOpenseadragon(); return () => { viewer && viewer.destroy(); }; }, []);

    return (

    export { OpenSeaDragonViewer };

    и просмотрщик файлов viewer.js

    import React, { useState } from "react";

    const Viewer = () => { const [image, setImage] = useState(null);

    const handleClick = (e) => { const id = e.target.id; const item = items.find((item) => item.id === id); setImage(item); };

    return ( <div id="openSeaDragon" style={{ height: "800px", width: "1200px" }} /> {items.map((item, index) => { return ( {item.title} ); })} Open ); };

    export default Viewer;

    Измени код в этих трех файлах так, чтобы при нажатии на каждое изображение из базы данных по полю items.preview происходил переход в новый компонент с просмотрщиком изображений openseadragon, и в этот компоненте открывался файл формата .dzi из базы данных из поля items.dzi.

  2. Assistant

    В файле Arachnoentomology.tsx измените код следующим образом:

    import React, { useEffect, useState } from "react";
    import Search from "./Search";
    import CustomizedHook from "./Tags";
    import { useHistory } from "react-router-dom";
    
    interface Item {
      id: number;
      title: string;
      preview: string;
      dzi: string;
    }
    
    const Arachnoentomology = () => {
      const [visible, setVisible] = useState(false);
      const [visible_hook, setVisible_hook] = useState(false);
      const [items, setItems] = useState<Item[]>([]);
      const history = useHistory();
    
      useEffect(() => {
        fetch("/api/tasks")
          .then((response) => response.json())
          .then((data) => setItems(data))
          .catch((error) => console.error(error));
      }, []);
    
      function toggleViewer(id: number) {
        const selectedItem = items.find(item => item.id === id);
        if (selectedItem) {
          history.push(`/viewer/${id}`);
        }
      }
    
      function toggleFilter() {
        setVisible_hook((prevVisible) => !prevVisible);
      }
    
      return (
        <div className="Arachnoentomology">
          <h1>Арахноэнтомология</h1>
          <p>
            Медицинская арахноэнтомология или медицинская энтомология — раздел
            медицинской паразитологии...
          </p>
          <br />
          <Search />
          <div className="filer_windows">
            <button onClick={toggleFilter}>Расширенный поиск</button>
            <br />
            <div className="tags_hooks">{visible_hook && <CustomizedHook />}</div>
            <br />
          </div>
          <ul>
            {items.map((item, index) => (
              <div key={index}>
                <a
                  href="#"
                  onClick={() => toggleViewer(item.id)}
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  <img src={item.preview} alt="description" />
                </a>
                <br />
                {item.title}
              </div>
            ))}
          </ul>
          <div className="gallery">
            <br />
          </div>
        </div>
      );
    };
    
    export default Arachnoentomology;
    

    В файле OpenSeaDragonViewer.tsx измените код следующим образом:

    import React, { useEffect, useState } from "react";
    import OpenSeaDragon from "openseadragon";
    import { useParams } from "react-router-dom";
    
    const OpenSeaDragonViewer = () => {
      const [viewer, setViewer] = useState<OpenSeaDragon.Viewer | null>(null);
      const { id } = useParams<{ id: string }>();
    
      useEffect(() => {
        fetch(`/api/tasks/${id}`)
          .then((response) => response.json())
          .then((data) => {
            if (viewer) {
              viewer.open(data.dzi);
            }
          })
          .catch((error) => console.error(error));
      }, [id, viewer]);
    
      useEffect(() => {
        const initOpenSeaDragon = () => {
          viewer && viewer.destroy();
          setViewer(
            OpenSeaDragon({
              id: "openSeaDragon",
              prefixUrl: "openseadragon-images/",
              animationTime: 0.5,
              blendTime: 0.1,
              constrainDuringPan: true,
              maxZoomPixelRatio: 2,
              minZoomLevel: 1,
              visibilityRatio: 1,
              zoomPerScroll: 2
            })
          );
        };
    
        initOpenSeaDragon();
    
        return () => {
          viewer && viewer.destroy();
        };
      }, []);
    
      return (
        <div
          id="openSeaDragon"
          style={{
            height: "800px",
            width: "1200px"
          }}
        ></div>
      );
    };
    
    export default OpenSeaDragonViewer;
    

    В файле Viewer.tsx измените код следующим образом:

    import React, { useState } from "react";
    import { useHistory } from "react-router-dom";
    
    interface Item {
      id: number;
      title: string;
      preview: string;
      dzi: string;
    }
    
    const Viewer = ({ items }: { items: Item[] }) => {
      const [image, setImage] = useState<Item | null>(null);
      const history = useHistory();
    
      const handleClick = (id: number) => {
        const selectedItem = items.find((item) => item.id === id);
        if (selectedItem) {
          setImage(selectedItem);
          history.push(`/viewer/${id}`);
        }
      };
    
      return (
        <div>
          <div id="openSeaDragon" style={{ height: "800px", width: "1200px" }} />
          <ul>
            {items.map((item) => (
              <li key={item.id}>
                <a href="#" onClick={() => handleClick(item.id)}>
                  <img src={item.preview} alt="description" />
                </a>
                <br />
                {item.title}
              </li>
            ))}
          </ul>
        </div>
      );
    };
    
    export default Viewer;
    

    Теперь у вас должно работать переключение на компонент просмотрщика изображений openseadragon при клике на каждое изображение.

  3. User

    const selectedItem = items.find(item => item.id === id); 107 | if (selectedItem) {

    108 | history.push(/viewer/${id}); | ^ 109 | } 110 | }

  4. Assistant

    Возникла ошибка в коде строки 108. Необходимо изменить ее следующим образом, чтобы правильно сформировать строку пути:

    history.push(`/viewer/${id}`);
    

    Обновленный код будет выглядеть так:

    import React, { useState } from "react";
    import { useHistory } from "react-router-dom";
    
    interface Item {
      id: number;
      title: string;
      preview: string;
      dzi: string;
    }
    
    const Viewer = ({ items }: { items: Item[] }) => {
      const [image, setImage] = useState<Item | null>(null);
      const history = useHistory();
    
      const handleClick = (id: number) => {
        const selectedItem = items.find((item) => item.id === id);
        if (selectedItem) {
          setImage(selectedItem);
          history.push(`/viewer/${id}`);
        }
      };
    
      return (
        <div>
          <div id="openSeaDragon" style={{ height: "800px", width: "1200px" }} />
          <ul>
            {items.map((item) => (
              <li key={item.id}>
                <a href="#" onClick={() => handleClick(item.id)}>
                  <img src={item.preview} alt="description" />
                </a>
                <br />
                {item.title}
              </li>
            ))}
          </ul>
        </div>
      );
    };
    
    export default Viewer;
    

    После внесения этой правки, ошибка будет исправлена, и код должен работать правильно.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.