javascript - React : _this. 状态未定义

标签 javascript reactjs

我写了以下代码片段:

export class Kurse extends React.Component {
  constructor(props) {
    super(props);

    this.state = {termineFreiburg: [
      {date: "21.02.2019", free: 10}, 
      {date: "02.05.2018", free: 0}, 
      {date: "13.03.2018", free: 10}, 
      {date: "04.07.2018", free: 12}, 
      {date: "05.08.2018", free: 12}
    ],
                termineKarlsruhe:[
      {date: "09.03.2019", free: 2},
      {date: "12.01.2018", free: 5}
    ]}
  }

  stadt = this.props.location.stadt;

  listItemsFreiburg = this.state.termineFreiburg.map((termin) =>
  <p><Link to={{pathname: "/bookCourse", datum: termin.date, stadt: this.props.location.stadt}}><Button>{termin.date}   Freie Plätze:  {(termin.free > 0)?termin.free:'ausgebucht'}</Button></Link></p>);

  listItemsKarlsruhe = this.state.termineKarlsruhe.map((termin) =>
  <p><Link to={{pathname: "/bookCourse", datum: termin.date, stadt: this.props.location.stadt}}><Button>{termin.date}   Freie Plätze:   </Button></Link></p>);

  render() {
    return(
      <div>
        <h2>Wähle Deinen Wunschtermin für einen Kurs in {this.props.location.stadt}</h2>
        {(this.props.location.stadt === 'Freiburg') ? this.listItemsFreiburg : this.listItemsKarlsruhe}
      </div>
    );
  }
}


export default Kurse;

预期结果:

我希望日期会出现在网站(应用程序页面)上。

实际结果:

我得到“_this.state未定义”,并突出显示“构造函数(props)”。

一旦我从构造函数中取出带有日期的代码片段,一切就都正常了!?

有什么帮助吗?或者提示?

最佳答案

类字段初始值设定项(例如用于创建 listItemsFreiburg 的类字段初始值设定项)在构造函数中的代码之前执行(它们实际上被插入到构造函数中调用 super 之后的开始)。例如,这个:

class Example {
    constructor(...args) {
        super(...args);
        this.answer = 42;
    }

    question = "Life, the Universe, and Everything";
}

实际上是这样的:

class Example {
    constructor(...args) {
        super(...args);
        this.question = "Life, the Universe, and Everything";
        this.answer = 42;
    }
}

注意顺序。详情见the class fields proposal .

这就是为什么当您调用 map 来创建 listItemsFreiburg 和其他时,state未定义一个。

使用字段初始值设定项来创建状态,或将类字段初始值设定项移至构造函数中。

但是,考虑到它们是基于状态的,在构建时构建它们似乎很奇怪。我会将它们作为本地变量移至 render 中,或者至少在状态更改时更新它们。

关于javascript - React : _this. 状态未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50372375/

相关文章:

javascript - 在 react 组件内等待来自非 react 源的请求

javascript - 使用映射函数将状态分配给动态渲染的组件

reactjs - 在 url 更改时,我想重新渲染我的组件,我应该怎么做

ruby-on-rails - API模式下Doorkeeper如何处理OAuth流程?

javascript - 安卓 WebView : is there a way to get a javascript stack trace?

javascript - 如何访问 bootstrap select onChange 事件中的 optgroup 值

javascript - 递归地重新创建嵌套对象数组

javascript - 基于范围内变量的 Angular 设置表单操作

javascript - SVG 与 React.js

javascript - 更改自定义元素的原型(prototype)