尽管已经绑定了函数,但尝试通过ReactJS更新状态时却看到以下错误。代码如下所示。该方法已绑定,console.log显示api返回正确的数据。
可能未处理的拒绝[1] TypeError:无法读取未定义的属性'setState'
import React from 'react';
import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table';
var rest, mime, client;
rest = require('rest');
mime = require('rest/interceptor/mime');
import ParameterDialog from './parameter-dialog';
const categoryAvailable = {
'POS': 'POS'
};
const options = {
noDataText: 'No parameters founds.'
}
function enumFormatter(cell, row, enumObject) {
return enumObject[cell];
}
export default class ParameterContainer extends React.Component {
constructor(props) {
super(props);
this.state = { parameters: [] };
this.client = rest.wrap(mime);
this.fetchFromApi = this.fetchFromApi.bind(this);
}
fetchFromApi() {
this.client({ path: '/api/parameters' }).then(function(response) {
console.log(response);
console.log(response.entity);
this.setState( {parameters: response.entity} );
});
}
componentDidMount() {
this.fetchFromApi();
}
render() {
return (
<div>
<h2>Parameters</h2>
<ParameterDialog />
<BootstrapTable data={this.state.parameters} options={options} pagination>
<TableHeaderColumn isKey dataField='id'>ID</TableHeaderColumn>
<TableHeaderColumn dataField='category' filterFormatted dataFormat={enumFormatter} formatExtraData={categoryAvailable}
filter={{type: 'SelectFilter', options: categoryAvailable}}>Category</TableHeaderColumn>
<TableHeaderColumn dataField='subCategory'>Sub Category</TableHeaderColumn>
<TableHeaderColumn dataField='parameter' filter={ { type: 'TextFilter', delay: 500 } }>Parameter</TableHeaderColumn>
<TableHeaderColumn dataField='type' filterFormatted dataFormat={enumFormatter} formatExtraData={this.props.parentState.parameterTypes}
filter={{type: 'SelectFilter', options: this.props.parentState.parameterTypes}}>Type</TableHeaderColumn>
<TableHeaderColumn dataField='roles'>Roles</TableHeaderColumn>
</BootstrapTable>
</div>
)
}
}
最佳答案
.then中的函数也必须被绑定
您可以使用()=>语法
fetchFromApi() {
this.client({ path: '/api/parameters' }).then(response => {
console.log(response);
console.log(response.entity);
this.setState( {parameters: response.entity} );
});
}
或者只是绑定功能
fetchFromApi() {
this.client({ path: '/api/parameters' }).then((function(response) {
console.log(response);
console.log(response.entity);
this.setState( {parameters: response.entity} );
}).bind(this);
}