【问题标题】:Unable to mount the component in react class based components无法在基于反应类的组件中安装组件
【发布时间】:2020-02-05 10:14:21
【问题描述】:

我正在使用 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"

我在这里错过了什么?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    这是错误的部分。

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

    应该是这样的:

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

    【讨论】:

    • 这个答案有效,但是当我点击刷新时还有另一个问题,showpopup 变为 false 并被重定向到 /。如果我应该在重新加载时显示弹出窗口,你建议我能做什么。你能把这段代码也展示一下吗?
    • 因为你已经在构造函数中初始化了 showpopup 所以它每次都会被调用。从构造函数中删除它并放在外面。
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      当你使用组件 props 时,路由器使用 React.createElement 从给定的组件创建一个新的 React 元素。这意味着如果 你为组件属性提供一个内联函数,你会 每次渲染创建一个新组件。这导致现有 组件卸载和新组件安装,而不仅仅是 更新现有组件。

      所以你的 line element.js 必须是

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

      而不是这个。

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

      还必须将路径更正为:

      路径={/:${this.props.elements.name}}

      【讨论】:

      • 技术上它会工作,但性能问题。请查看我在答案中提供的教程。
      猜你喜欢
      • 2020-08-27
      • 2022-01-27
      • 2020-04-28
      • 2020-12-27
      • 2019-03-11
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多