【发布时间】:2019-03-04 20:03:03
【问题描述】:
我有一个名为 postdata.js 的函数组件文件,我在 app.js 中使用它。在 postdata 内部,我有一个从 API 获取值的函数(正在工作)。但是当我在调用的 postdata 函数中使用 this.setState 并将其分配给 API 结果值时,我会抛出一个错误:
Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined
postdata.js:
export function Postdata(url=''){
return fetch(url).then(
function(response){
console.log("response.json()::",response)
return response.json();
})
}
app.js:
import React, { Component } from 'react';
import logo from './logo.svg';
import {Table} from 'reactstrap';
import './App.css';
import {Postdata} from './postdata';
class App extends React.Component {
constructor(props){
super(props);
this.state = {
hits: 'sduhyh',
result_:[]
}
//this.Postdata = this.Postdata.bind(this)
}
componentDidMount() {}
postdata_fire(){
Postdata('http://localhost:3000/places').then(function(result){
console.log("result::",result);
this.setState({result:'sdujoij'})
})
this.setState({hits:'yahittsss'})
console.log("hits:::",this.state.hits);
}
render() {
return (
<div className="App container">
<div>{this.state.hits}</div>
<button onClick={this.postdata_fire.bind(this)}></button>
</div>
);
}
}
export default App;
请帮忙。
【问题讨论】:
标签: reactjs