Реагировать this.props не определено в событии состояния? - PullRequest
0 голосов
/ 06 марта 2020

Я пытаюсь использовать значение props в dataPointSelection в apexchart в состоянии, но получаю ошибку, что this.props не определено, а также значение не отображается в журнале консоли. Вот мой код, который я сделал:

constructor(props) {
    super(props);
    const { t, too, fromm } = this.props;
    console.log("Upper" + this.props.fromm);
    this.state = {
      ...props,
      options: {
        chart: {
          id: "Speeding",
          events: {
            dataPointSelection: function(event, chartContext, opts) {
              switch (opts.w.config.xaxis.categories[opts.dataPointIndex]) {
                case "0-10":
                  window.open(
                    window.location.origin +
                      `/overspeeding/10/0/${
                        this.props.too ? `${this.props.too}` : `${cc}`
                      }/${
                        this.props.fromm ? `${this.props.fromm}` : "2016-01-04"
                      }` // in this line i am getting error
                  );

Как устранить эту ошибку и значение реквизита пользователя в событии?

Ответы [ 2 ]

3 голосов
/ 06 марта 2020

Обычно вам не нужно это за реквизитом в конструкторе. Попробуйте просто реквизит

1 голос
/ 06 марта 2020

Проблема в том, что внутри function у вас нет доступа к тому же this, что и в конструкторе. Вместо этого у вас есть доступ к переданному props объекту, который содержит реквизиты.

Все будет в порядке, просто заменив this.props на props там:

constructor(props) {
    super(props);
    const { t, too, fromm } = props;
    console.log("Upper" + props.fromm);
    this.state = {
      ...props,
      options: {
        chart: {
          id: "Speeding",
          events: {
            dataPointSelection: function(event, chartContext, opts) {
              switch (opts.w.config.xaxis.categories[opts.dataPointIndex]) {
                case "0-10":
                  window.open(
                    window.location.origin +
                      `/overspeeding/10/0/${
                        props.too ? `${props.too}` : `${cc}`
                      }/${
                        props.fromm ? `${props.fromm}` : "2016-01-04"
                      }` // in this line i am getting error
                  );

Другой способ будет связывать верхний this с новой функцией, используя .bind(this), или просто используя функцию стрелки, которая не имеет своего собственного `this:

constructor(props) {
    super(props);
    const { t, too, fromm } = this.props;
    console.log("Upper" + this.props.fromm);
    this.state = {
      ...props,
      options: {
        chart: {
          id: "Speeding",
          events: {
            dataPointSelection: (event, chartContext, opts) => { // Arrow funciton
              switch (opts.w.config.xaxis.categories[opts.dataPointIndex]) {
                case "0-10":
                  window.open(
                    window.location.origin +
                      `/overspeeding/10/0/${
                        this.props.too ? `${this.props.too}` : `${cc}`
                      }/${
                        this.props.fromm ? `${this.props.fromm}` : "2016-01-04"
                      }` // in this line i am getting error
                  );

Используя function.bind:

constructor(props) {
    super(props);
    const { t, too, fromm } = this.props;
    console.log("Upper" + this.props.fromm);
    this.state = {
      ...props,
      options: {
        chart: {
          id: "Speeding",
          events: {
            dataPointSelection: function(event, chartContext, opts) {
              switch (opts.w.config.xaxis.categories[opts.dataPointIndex]) {
                case "0-10":
                  window.open(
                    window.location.origin +
                      `/overspeeding/10/0/${
                        this.props.too ? `${this.props.too}` : `${cc}`
                      }/${
                        this.props.fromm ? `${this.props.fromm}` : "2016-01-04"
                      }` // in this line i am getting error
                  );
                  // ...
                }
              }.bind(this)// Binding the upper this to function scope.
            // ...

...