无法读取react的未定义n fetch方法的属性'setState'

时间:2018-05-24 15:31:02

标签: reactjs setstate

我正在使用google contact api获取联系人。

在fetch方法的响应中,我收到所有联系人。但是使用setState设置状态时,它会给出Cannot read property 'setState' of undefined的错误。这是我的代码。

我也经历了他的教程,但未能在此找到extact问题。

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';


class App extends Component {
    constructor(props) {
        super(props)
        this.auth = this.auth.bind(this);
        this.state = {
            userarray: []
        }

    }
    auth() {
        var config = {
            'client_id': 'my-client-id',
            'scope': 'https://www.google.com/m8/feeds'
        };
        window.gapi.auth.authorize(config, function () {
            alert("Dd")
            // this.fetchtt(window.gapi.auth.getToken());  
            fetch("https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=" + window.gapi.auth.getToken().access_token + "&max-results=700&v=3.0", {
                method: 'GET'
            })
                .then((result) => {
                    result.json().then((result) => {

                        // display all your data in console
                        console.log(result.feed);
                        result.feed.entry.map((entry, index) => {

                            console.log(entry.title.$t)
                            const user = [
                                name => entry.title.$t
                            ]
                            this.setState({
                                userarray: "ss"
                            });
                        })
                    })
                }
                )

        });
    }





    render() {
        return (
            <div className="App">
                <header className="App-header">
                    <img src={logo} className="App-logo" alt="logo" />
                    <h1 className="App-title">Welcome to React</h1>
                </header>
                <p className="App-intro">
                    To get started, edit <code>src/App.js</code> and save to reload.
        </p>
                <button onClick={() => this.auth()}>GET CONTACTS FEED</button>
            </div>
        );
    }
}

export default App;

1 个答案:

答案 0 :(得分:2)

window.gapi.auth.authorize(config, function () {会改变回调使用window.gapi.auth.authorize(config, () => {中的上下文。

PS你不需要嵌套你的 -

.then(result => result.json())
.then(result => { ... })