【问题标题】:es6 arrow function in class property类属性中的 es6 箭头函数
【发布时间】:2018-06-28 08:36:34
【问题描述】:

我将代码与./node_modules/.bin/webpack -d 捆绑在一起。除了class fields proposal,我没有将 ES6 编译为 ES5。

它给出了这个错误:

未捕获的类型错误:this.fetchTestExecutions 不是函数

代码如下:

import React from 'react'
import Config from 'Config'

class HomePage extends React.Component {

  state = {
    executions: this.fetchTestExecutions()
  }

  fetchTestExecutions = () => {
    const host = Config.host
    return fetch(`${host}/execution/index`)
      .then(response => response.json())
      .then(json => {
        this.setState({executions: json})
      })
  }

  render() {
    return(
      <div>
        { this.state.executions.map(x => <div>x.from</div>) }
      </div>
    )
  }
}

export default HomePage

这是 webpack.config.js:

var webpack = require('webpack')

module.exports = {
  entry: './src/App.jsx',
  output: {
    filename: './../public/bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        query: {
          plugins: ['transform-class-properties'],
          presets: ['react'],
        }
      }
    ]
  },
  externals: {
    'Config': JSON.stringify({host: "http://127.0.0.1:3000"})
  }
}

怎么了?

感谢您的宝贵时间!

【问题讨论】:

    标签: reactjs class ecmascript-6 arrow-functions


    【解决方案1】:

    将方法(特别是 api 调用)设置为状态属性不是一个好的模式。相反,更喜欢在生命周期事件中首先调用 api,然后再设置状态。

    class HomePage extends React.Component {
      state = {
        executions: []
      }
    
      componentDidMount() {
        const host = Config.host
    
        fetch(`${host}/execution/index`)
          .then(response => response.json())
          .then(json => this.setState({ executions: json }))
      }
    
      render() {
        return(
          <div>
            { this.state.executions.map(x => <div>x.from</div>) }
          </div>
        )
      }
    }
    

    【讨论】:

    • 他没有设置方法,他设置了从该方法返回的承诺。但是,这绝对是一个非常糟糕的模式。
    • 是的,当然。这只是解释不良模式的一种手段:)
    • 嗨@mersocarlin,感谢关于设置状态的建议。如果我得到另一个randomString = () =&gt; "a string"state = { executions: this.randomString()} 怎么办?它仍然给出同样的错误。 state 是类变量吗? this.randomString()是实例方法?
    • @mCY state 是一个对象 link to docs。而且我不会使用方法(例如randomString)来设置其初始属性。 this.randomString() 是一个实例方法,如果您在组件内定义它(允许您从组件内的任何位置调用 this.randomString())。
    【解决方案2】:

    类字段(目前是第 2 阶段提案)在类实例化时分配。原始代码等于这个 ES6 代码:

    class HomePage extends React.Component {
      constructor() {
        this.state = {
          executions: this.fetchTestExecutions()
        };
    
        this.fetchTestExecutions = () => { /*...*/ };
      }
      ...
    }
    

    看起来,顺序很重要,fetchTestExecutions 在被调用时是未定义的。

    为了使其工作,fetchTestExecutions 类字段应在state 之前定义。

    除非fetchTestExecutions 被用作回调(它不是),它肯定应该是原型方法(已经在另一个答案中建议):

    class HomePage extends React.Component {
      state = {
        executions: this.fetchTestExecutions()
      }
    
      fetchTestExecutions() { /*...*/ }
      ...
    }
    

    这消除了问题并产生更高效的代码。另请参阅this explanation,了解箭头(实例)和原型方法之间的实际区别。

    【讨论】:

      【解决方案3】:

      你必须像这样改变你的功能

      fetchTestExecutions(){
      const host = Config.host
      return fetch(`${host}/execution/index`)
        .then(response => response.json())
        .then(json => {
          this.setState({executions: json})
        })
      }
      

      【讨论】:

        猜你喜欢
        • 2018-08-01
        • 2019-01-06
        • 1970-01-01
        • 2016-09-07
        • 2022-01-21
        • 2016-03-25
        • 2019-05-23
        相关资源
        最近更新 更多