【问题标题】:Spread Notation in React.js render function and Variable ScopeReact.js 渲染函数和变量范围中的扩展符号
【发布时间】:2019-03-27 15:50:13
【问题描述】:

我有一个使用 es6 类符号定义的反应组件。在渲染函数中,我尝试使用扩展符号将一些状态变量传递给子组件:

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

这不起作用:data is not defined。使用this.state.datastate.data 也不起作用(导致Unexpected keyword 'this'Unexpected token)。

但是,取消注释 &lt;div&gt;{console.log(this.state.data)}&lt;/div&gt; 表明状态在范围内。最后,这是可行的:

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

在这种情况下,我是否以某种方式滥用了扩展符号?我已经看到它在 React 函数组件中工作。

【问题讨论】:

  • 当您指定对象时,它允许您跳过值 IF 名称与变量匹配。好像你在任何地方都没有data,所以它应该是...{ data: this.state.data, //other props here },或者你可以在return语句之前做const { data } = this.state

标签: javascript reactjs scope


【解决方案1】:

我认为您使用了错误的变量。 data 确实是未定义的。你的实际数据在this.state.data

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

你能试试这个吗?

【讨论】:

  • 看起来像是一种我不熟悉的特定于 JSX 的用法(而且很方便)。刚刚试了一下,效果很好。可能会在return:const {data, columns} = this.state;(和infinite? 无法从问题中看出)之前添加解构然后OP 的版本(假设infinite 在某个范围内)会起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多