首页 > 解决方案 > 如何以刷新后的方式设置数据它也保持在那里反应

问题描述

我正在尝试使用 node 和 mongo 制作一个反应项目,我将在其中显示我的元素周期表 onclick 我将更新链接并显示带有数据的弹出窗口。这是json数据

{
    "elements": [
        {
            "name": "Hydrogen", 
            "appearance": "colorless gas", 
            "atomic_mass": 1.008, 
            "boil": 20.271, 
            "category": "diatomic nonmetal", 
            "color": null, 
            "density": 0.08988, 
            "discovered_by": "Henry Cavendish", 
            "melt": 13.99, 
            "molar_heat": 28.836, 
            "named_by": "Antoine Lavoisier", 
            "number": 1, 
            "period": 1, 
            "phase": "Gas", 
            "source": "https://en.wikipedia.org/wiki/Hydrogen", 
            "spectral_img": "https://en.wikipedia.org/wiki/File:Hydrogen_Spectra.jpg", 
            "summary": "Hydrogen is a chemical element with chemical symbol H and atomic number 1. With an atomic weight of 1.00794 u, hydrogen is the lightest element on the periodic table. Its monatomic form (H) is the most abundant chemical substance in the Universe, constituting roughly 75% of all baryonic mass.", 
            "symbol": "H", 
            "xpos": 1, 
            "ypos": 1, 
            "shells": [
                1
            ],
            "electron_configuration": "1s1",
            "electron_affinity": 72.769,
            "electronegativity_pauling": 2.20,
            "ionization_energies": [
                1312.0
            ]
        }, 
        {
            "name": "Helium", 
            "appearance": "colorless gas, exhibiting a red-orange glow when placed in a high-voltage electric field", 
            "atomic_mass": 4.0026022, 
            "boil": 4.222, 
            "category": "noble gas", 
            "color": null, 
            "density": 0.1786, 
            "discovered_by": "Pierre Janssen", 
            "melt": 0.95, 
            "molar_heat": null, 
            "named_by": null, 
            "number": 2, 
            "period": 1, 
            "phase": "Gas", 
            "source": "https://en.wikipedia.org/wiki/Helium", 
            "spectral_img": "https://en.wikipedia.org/wiki/File:Helium_spectrum.jpg", 
            "summary": "Helium is a chemical element with symbol He and atomic number 2. It is a colorless, odorless, tasteless, non-toxic, inert, monatomic gas that heads the noble gas group in the periodic table. Its boiling and melting points are the lowest among all the elements.", 
            "symbol": "He", 
            "xpos": 18, 
            "ypos": 1, 
            "shells": [
                2
            ],
            "electron_configuration": "1s2",
            "electron_affinity": -48,
            "electronegativity_pauling": null,
            "ionization_energies": [
                 2372.3, 
                 5250.5
            ]
        }, 
        {
            "name": "Lithium", 
            "appearance": "silvery-white", 
            "atomic_mass": 6.94, 
            "boil": 1603, 
            "category": "alkali metal", 
            "color": null, 
            "density": 0.534, 
            "discovered_by": "Johan August Arfwedson", 
            "melt": 453.65, 
            "molar_heat": 24.86, 
            "named_by": null, 
            "number": 3, 
            "period": 2, 
            "phase": "Solid", 
            "source": "https://en.wikipedia.org/wiki/Lithium", 
            "spectral_img": null, 
            "summary": "Lithium (from Greek:\u03bb\u03af\u03b8\u03bf\u03c2 lithos, \"stone\") is a chemical element with the symbol Li and atomic number 3. It is a soft, silver-white metal belonging to the alkali metal group of chemical elements. Under standard conditions it is the lightest metal and the least dense solid element.", 
            "symbol": "Li", 
            "xpos": 1, 
            "ypos": 2, 
            "shells": [
                2,
                1
            ],
            "electron_configuration": "1s2 2s1",
            "electron_affinity": 59.6326,
            "electronegativity_pauling": 0.98,
            "ionization_energies": [
                520.2, 
                7298.1,
                11815.0

            ]
        }]}

我的代码中的问题是,每当有人手动设置 URL 时,它不会获得带有数据的默认弹出窗口。我希望网址是动态的,但可以访问。我使用元素名称作为反应链接,通过传递要在弹出窗口中显示的元素的详细信息,将其重定向到呼叫路由。

这是我的 react App.js文件

import React, { useEffect, useState } from 'react';
import './App.css';
import axios from 'axios';
import Element from './components/Element';
function App() {
  // const context = React.createContext();
  const [elements, setElements] = useState([]);

  useEffect(() => {
    const res = async () => {
      const result = await axios.get('/data');
      const data = result.data;
      setElements(elements => [...elements, ...data]);
    };
    res();
  }, []);
  // console.log(elements.map(element => console.log(element)));
  return (
    <div className='wrapper'>
      <div id='table'>
        {elements.map(element => (
          <Element elements={element} key={element._id} />
        ))}
      </div>
    </div>
  );
}

export default App;

在 App.js 中,我正在获取数据并将其映射以发送到要在前端显示的元素。

元素.js

import React, { useState } from 'react';
import {
  BrowserRouter as Router,
  Redirect,
  Route,
  Link
} from 'react-router-dom';
import Popup from './Popup';
const Element = ({ elements }) => {
  const { symbol, category, name, number } = elements;
  const [showPopup, setPopup] = useState(false);
  const test = window.location.pathname;
  console.log(abc === '/' ? 'yes' : 'no');
  const handleClick = () => {
    setPopup(!showPopup);
  };
  return (
    <Router>
      <div
        onClick={() => handleClick()}
        title={name}
        className={`element element-${number} ${category}`}
      >
        {' '}
        <Link to={name}>
          <div className='symbol'>{symbol}</div>
        </Link>
        {showPopup ? (
          <Route
            exact
            path='/:name'
            component={() => <Popup element={elements} />}
          />
        ) : (
          <Redirect to='/' />
        )}
      </div>
    </Router>
  );
};

export default Element;

在 Element.js 中,我试图从 app.js 获取道具,然后单击任何显示数据和更新链接的元素。当他们再次单击时,我将弹出变量设置为 false,从而重定向到主页。

Popup.js

import React from 'react';
// import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
const Popup = ({ element }) => {
  console.log(element);
  const { category } = element;
  return (
    <div className='popup'>
      <center>
        <div className={`popupInner ${category}`}>
          {Object.entries(element).map(([key, val]) => (
            <h2 key={key}>
              {key}: {val ? val : 'unknown'}
            </h2>
          ))}
        </div>
      </center>
    </div>
  );
};

export default Popup;

在 Popup.js 中,我通过映射内容来显示数据详细信息。

请告诉我我该怎么做?当 showPopup 为假时,我将重定向到“/”。请提供代码的建议和描述。

标签: javascriptreactjs

解决方案


推荐阅读