无法使用fetch将API数据绑定到React JS中的this.setState

问题描述 投票:0回答:1

我是React JS的新手,我在通过fetch 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;
javascript reactjs typescript
1个回答
0
投票

您收到此错误是因为users未在回调函数的范围内定义(在Fetch中)。用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
       });   
  }
© www.soinside.com 2019 - 2024. All rights reserved.