![](/img/trans.png)
[英]Using this.setState in the callback of this.setState in React JS?
[英]Unable to bind API data to this.setState in React JS using fetch
我是React JS的新手,在通過訪存API調用在表中顯示數據時遇到問題。 能夠獲取JSON數據,但無法將數據綁定到this.State對象。 它總是拋出以下錯誤。
index.bundle.js:49未捕獲的ReferenceError:未定義用戶
我可以知道做錯了什么嗎。 這是我的代碼。
import React, {Component} from "react";
import { Badge, Row, Col, Card, CardHeader, CardBlock, Table, Pagination, PaginationItem, PaginationLink} from "reactstrap";
class Users extends Component {
constructor(){
super();
this.state={users:[]};
}
componentDidMount(){
fetch('http://some_ip_address/api/subuserlist',{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'filterfield': 'group_id',
'filtervalue': 'random_filter_value'
}
}).then(result=>result.json())
.then(function(data) {
console.log(data); //able to print data
this.setState({users:data});
console.log(users); //unable to print users
}.bind(this))
.catch(function(error) {
// If there is any error you will catch them here
});
}
render() {
return (
<div className="animated fadeIn">
<Row>
<Col>
<Card>
<CardHeader>
<i className="fa fa-align-justify"></i> Combined All Table
</CardHeader>
<CardBlock className="card-body">
<table>
<tbody>
{this.state.users && this.state.users.map(function(users) {
return (
<tr>
<td>{users.firstName}</td>
</tr>
)
})}</tbody>
</table>
</CardBlock>
</Card>
</Col>
</Row>
</div>
);
}
}
export default Users;
您收到此錯誤是因為未在回調函數的范圍內(在Fetch中)定義users
。 替換console.log(users);
與console.log(this.state.users);
。 另外,你得給你的回調從一個普通的匿名功能箭頭功能改變,否則this
將不是指你的類,它會指回調函數。
componentDidMount(){
fetch('http://some_ip_address/api/subuserlist',{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'filterfield': 'group_id',
'filtervalue': 'random_filter_value'
}
}).then(result=>result.json())
.then((data) => {
console.log(data); //able to print data
this.setState({
users:data
}, () => {
console.log(this.state.users); // This will be fired after setState has completed.
});
})
.catch(function(error) {
// If there is any error you will catch them here
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.