繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM