简体   繁体   中英

Spread Notation in React.js render function and Variable Scope

I have a react component that is defined using es6 class notation. In the render function I'm trying to pass some state variables into a sub-component using the spread notation:

  render() {
    return (
      // <div>{console.log(this.state.data)}</div>
      <Table 
        {...{
          data,
          columns,
          infinite,
          debug: true
        }} 
      />
    );
  }

This didn't work: data is not defined . Using this.state.data and state.data doesn't work either (results in Unexpected keyword 'this' and Unexpected token ).

However, uncommenting <div>{console.log(this.state.data)}</div> shows that state is in scope. Finally, this works:

<Table data={this.state.data} columns={this.state.columns}/>

Am I somehow misusing spread notation in this case? I've seen it work in React function components.

I think you're using the wrong variables. data is indeed undefined. You're actual data lies in this.state.data

render() {
    return (
      // <div>{console.log(this.state.data)}</div>
      <Table 
        {...{
          data: this.state.data,
          columns: this.state.columns,
          infinite,
          debug: true
        }} 
      />
    );
  }

Could you try this?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM