无法读取属性' setState'未定义的(使用fetch api)

时间:2017-06-13 13:30:37

标签: reactjs

当我试图设置我的"用户"状态变量,我收到以下消息:
无法读取属性' setState'未定义的
它在以下代码行中:

this.setState({users: data.users});

这是我的班级

` 导入React,{Component}来自'反应&#39 ;;

类用户扩展了组件{

constructor(props) {
    super(props);
    this.state = {
        users: []
    };
}

componentWillMount() {
    this.getUsers();
}

getUsers = () => {
    let myHeaders = new Headers({
        'Authorization': 'Basic '+btoa('john@doe.com:password'),
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    });

    fetch('https://dev-api/v1/user/', {
        method: 'GET',
        headers: myHeaders
    }).then(function(response) {
        if (!response.ok) {
            throw Error(response.statusText);
        }
        return response;
    }).then(function(response) {
        response.json().then(function(data) {
            this.setState({users: data.users});
        });
    }).catch(function(error) {
        console.log(error);
    });
}

render() {
    return (
        <table className="striped bordered">
            <thead>
                <tr>
                    <th>email</th>
                    <th>Firstname</th>
                    <th>Lastname</th>
                </tr>
            </thead>
            <tbody>
            {this.state && this.state.users && this.state.users.map(user =>
                <tr>
                    <td>{user.username}</td>
                    <td>{user.firstname}</td>
                    <td>{user.lastname}</td>
                </tr>
            )}
            </tbody>
      </table>
    );
}

}

导出默认用户;`

非常感谢!

1 个答案:

答案 0 :(得分:1)

constructor(props) {
    super(props);
    this.state = {
        users: []
    };
   this.getUsers = this.getUsers.bind(this); //************ add this
}

getUsers = () => {
    let self = this //************ add this
    let myHeaders = new Headers({
        'Authorization': 'Basic '+btoa('john@doe.com:password'),
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    });

    fetch('https://dev-api/v1/user/', {
        method: 'GET',
        headers: myHeaders
    }).then(function(response) {
        if (!response.ok) {
            throw Error(response.statusText);
        }
        return response;
    }).then(function(response) {
        response.json().then(function(data) {
            self.setState({users: data.users}); //****** replace this
        });
    }).catch(function(error) {
        console.log(error);
    });
}