【问题标题】:How do I import a class with its updated state in React.js如何在 React.js 中导入具有更新状态的类
【发布时间】:2020-07-15 04:49:57
【问题描述】:

我有一个名为 Scanned.js 的类,它的初始状态为

export default class Scanned extends Component {
    constructor(props) {
    super(props);
    this.state = {
          name: "No Name Found",
          licensePlate: "No License Plate Found",
          registrationNumber: "No Number Found",
          referencePlate: "No Plate to Reference"
    };

然后它会在 Scanned.js 的渲染部分中更新,以便

this.state = {
      name: "No Name Found",
      licensePlate: "Jon",
      registrationNumber: "FJG-333",
      referencePlate: "FJG-333"
    };

然后我转到另一个文件并执行

import Scanned from "./Scanned";

console.log(Scanned.state.name);

我得到一个错误。我做错了什么,如何正确导入类,以便获取属于该状态的更新值并使用名称值?

【问题讨论】:

  • 你得到哪个错误?
  • 我收到一条错误消息,提示“无法获取未定义或空引用的属性‘名称’”。

标签: class import export state reactjs


【解决方案1】:

试试这个:

export var props_scanned;
export default class Scanned extends Component {
    constructor(props) {
    super(props);
    this.state = {
          name: "No Name Found",
          licensePlate: "No License Plate Found",
          registrationNumber: "No Number Found",
          referencePlate: "No Plate to Reference"
    };
    props_scanned = this

}

现在在另一个文件中,

确保正确定义了导入路径。

import {props_scanned} from './Scanned';

console.log(props_scanned.state.name);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    • 2018-02-19
    • 2014-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多