在类属性中使用ES6箭头函数

3

我使用./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"})
  }
}

有什么问题吗?

感谢您的时间!

3个回答

3

将方法(特别是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>
    )
  }
}

5
他并没有设置方法,而是设置了从该方法返回的Promise。然而,这绝对是一个非常糟糕的模式。 - Sulthan
是的,当然。这只是一种解释不好的模式的方式 :) - Hemerson Carlin
嗨@mersocarlin,感谢您关于设置状态的建议。如果我有另一个randomString =()=>“a string”state = {executions:this.randomString()},它仍然会给出相同的错误。 state是类变量吗?this.randomString()是实例方法吗? - mCY
@mCY state 是一个对象文档链接。我不会使用方法(例如randomString)来设置它的初始属性。如果您在组件内定义了this.randomString(),则它是一个实例方法(允许您从组件内的任何位置调用this.randomString())。 - Hemerson Carlin

2

类字段(目前是第二阶段提案)在类实例化时被赋值。原始代码等同于这个ES6代码:

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

    this.fetchTestExecutions = () => { /*...*/ };
  }
  ...
}

显然,顺序很重要,当调用fetchTestExecutions时,它此时是未定义的。

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

除非fetchTestExecutions被用作回调(并且它没有被用作回调),否则它应该成为原型方法(另一个答案已经建议了这一点):

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

  fetchTestExecutions() { /*...*/ }
  ...
}

这将消除问题,使代码更加高效。另请参见此解释,了解箭头(实例)和原型方法之间的实际区别。

1
你必须像这样更改你的函数。
fetchTestExecutions(){
const host = Config.host
return fetch(`${host}/execution/index`)
  .then(response => response.json())
  .then(json => {
    this.setState({executions: json})
  })
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接