我目前正在尝试把头放在React中如何实现典型的数据结构。以队列为例,据我了解,如果我使用Java创建队列,则可以使用以下Javascript转换格式定义函数:

class Queue extends Component {

  constructor(props) {
    super(props);
    this.state = {message: "Test"}
  }

  queue(el) {
    let arr = this.state.arr.slice();
    arr.push(el);
    return arr;
  }

  dequeue = (el) => {
    let arr = this.state.arr.slice(1, this.state.arr.length);
    return arr;
  }

  next = () => {
    let arr = this.state.arr.slice();
    return arr[1];
  }

  last = () => {
    let arr = this.state.arr.slice();
    return arr[arr.length - 1];
  }
}


并以main()方法访问它。但是,在这种情况下,我将使用父组件,其示例如下所示:

class Main extends Component {

  constructor(props) {
    this.state = {queue: new Queue()};
  }

  render() {
    console.log(this.state.queue);
    //displays the queue with its listed functions properly

    this.state.queue(new Date());
    //ERROR: 'cannot read property "slice" of undefined'
  }
}


因此,我可以弄清楚Main类从Queue类访问函数queue()的明显发生,但是将其绑定到Main类而不是按预期的方式绑定到Queue类。

所以我的问题是:使用ES6箭头语法,如何维护Main类中使用的this与queue的子实例而不是调用方法的Main类的绑定?

换句话说,如何确保访问this.state.arr变量引用存储在Queue队列实例中的arr而不是Main类状态下未声明的arr?

如果这是一个重复的问题,我事先表示歉意,但是对于这种特殊情况,搜索没有给我任何答案,因此,我们将非常感谢您的帮助。

编辑:正如西德尼在下面指出的那样,我犯了一个愚蠢的错误,并从队列组件的状态中省略了arr。抱歉!

最佳答案

您实际上得到的错误与this绑定无关,如果在React之外使用Queue类,则会发生此错误。



class Queue {
  constructor(props) {
    this.state = {message: "Test"}
  }

  queue(el) {
    let arr = this.state.arr.slice();
    arr.push(el);
    return arr;
  }

  dequeue = (el) => {
    let arr = this.state.arr.slice(1, this.state.arr.length);
    return arr;
  }

  next = () => {
    let arr = this.state.arr.slice();
    return arr[1];
  }

  last = () => {
    let arr = this.state.arr.slice();
    return arr[arr.length - 1];
  }
}

const ticketLine = new Queue()
ticketLine.queue('Bob')
ticketLine.queue('Sarah')





(注意已删除extends Componentsuper()

该错误发生在queue()的第一行,您正在尝试访问this.state.arr,但从未定义过它。因此,对未定义调用.slice()会引发错误。

10-04 22:53
查看更多