我将代码与./node_modules/.bin/webpack -d
捆绑在一起。除了class fields proposal
之外,我没有将ES6编译为ES5。
它给出了这个错误:
未捕获的TypeError: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"})
}
}
怎么了?
谢谢你的时间!
答案 0 :(得分: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>
)
}
}
答案 1 :(得分: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 arrow(实例)和原型方法之间的实际区别。
答案 2 :(得分:1)
你必须像这样改变你的功能
fetchTestExecutions(){
const host = Config.host
return fetch(`${host}/execution/index`)
.then(response => response.json())
.then(json => {
this.setState({executions: json})
})
}