无法将组件安装在基于React类的组件中

时间:2019-10-08 06:16:21

标签: javascript reactjs

我正在使用react 16.8我使用钩子和功能组件创建了一个项目,现在我试图使其成为基于类的组件,但是没有安装一个组件。在app.js中,我正在componentDidUpdate中获取数据,它工作正常,没有任何问题。 Element.js还在渲染组件并创建onclick链接,我正在更新状态并通过传递不起作用的道具来调用弹出组件。

App.js

import React, { Component } from 'react';
import './App.css';
import axios from 'axios';
import Element from './components/Element';
class App extends Component {
  constructor(props) {
    super(props);
    this.state = { elements: [] };
  }
  componentDidMount() {
    const res = async () => {
      const result = await axios.get('/data');
      const data = result.data;
      this.setState({ elements: data });
    };
    res();
  }
  render() {
    return (
      <div className='wrapper'>
        <div id='table'>
          {this.state.elements.map(element => (
            <Element elements={element} key={element._id} />
          ))}
        </div>
      </div>
    );
  }
}

export default App;

在Element.js中,我正在为所有元素创建链接并创建路由部分。 Onclick使showpopup为true,并将道具传递给popup。 当弹出消息被称为外部路由时,它正在工作。但是在每个组件上单击,我必须传递不同的道具并显示相同的弹出窗口。 Element.js

import React, { Component } from 'react';
import {
  BrowserRouter as Router,
  Redirect,
  Route,
  Link
} from 'react-router-dom';
import Popup from './Popup';
class Element extends Component {
  constructor(props) {
    super(props);
    this.state = { showPopup: false };
  }

  handleClick = () => {
    this.setState({ showPopup: !this.state.showPopup });
  };

  render() {
    return (
      <Router>
        <div
          onClick={this.handleClick}
          title={this.props.elements.name}
          className={`element element-${this.props.elements.number} ${this.props.elements.category}`}
        >
          {' '}
          <Link to={this.props.elements.name}>
            <div className='symbol'>{this.props.elements.symbol}</div>
          </Link>
          {this.state.showPopup ? (
            <Route
              exact
              path='/:this.props.elements.name'
              component={props => <Popup element={this.props.elements} />}
            />
          ) : (
            <Redirect to='/' />
          )}
        </div>
      </Router>
    );
  }
}

export default Element;

Popup.js //未安装

import React, { Component } from 'react';

class Popup extends Component {
  constructor(props) {
    super(props);
    console.log(this.props.element);
  }
  render() {
    return (
      <div className='popup'>
        <center>
          <div className={`popupInner ${this.props.elements.category}`}>
            {Object.entries(this.props.elements).map(([key, val]) => (
              <h2 key={key}>
                {key}: {val ? val : 'unknown'}
              </h2>
            ))}
          </div>
        </center>
      </div>
    );
  }
}

export default Popup;

这里是JSON之一

appearance: "colorless gas"
atomic_mass: 1.008
boil: 20.271
category: "diatomic nonmetal"
color: null
density: 0.08988
discovered_by: "Henry Cavendish"
electron_affinity: 72.769
electron_configuration: "1s1"
electronegativity_pauling: 2.2
ionization_energies: [1312]
melt: 13.99
molar_heat: 28.836
name: "Hydrogen"
named_by: "Antoine Lavoisier"
number: 1
period: 1
phase: "Gas"
shells: [1]
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
_id: "5d90c80f6adf8a1c62f4fdb4"

我在这里想念什么?

3 个答案:

答案 0 :(得分:1)

这是错误的部分。

 path='/:this.props.elements.name'

应如下所示:

 path={`/:${this.props.elements.name}`}

答案 1 :(得分:1)

您提供的路径只是一个字符串,因此将其更改为如下所示的表达式。

<Route
  exact
  path={`/:${this.props.elements.name}`}
  component={props => <Popup element={this.props.elements} />}
/>;

答案 2 :(得分:1)

通过此链接(https://tylermcginnis.com/react-router-pass-props-to-components):

  

使用组件道具时,路由器使用React.createElement   从给定的组件创建一个新的React元素。那意味着   您向component属性提供了一个内联函数,您将   在每个渲染器中创建一个新组件。这导致现有   组件卸载和新组件安装,而不仅仅是   更新现有组件。

因此您的line element.js必须是

 render={props => <Popup element={this.props.elements} />}

代替这个。

 component={props => <Popup element={this.props.elements} />}

还可以将路径更正为:

path = {{/:${this.props.elements.name}}