无法在 React 中使用 Fetch API 获取数据

Unable to get data using Fetch API in React

我有以下函数可以调用 api 并获取数据。

export function getUserData(url){

  return fetch(url, { credentials : 'include'})
              .then((response) => { return response.json()})
              .then((data) =>{ return new User(data.uid, data.givenName, data.familyName)})
}

这是我的用户对象。

class User{
  constructor(uid, givenName, familyName){

    this.uid = yguid;
    this.givenName = givenName;
    this.familyName = familyName;
  }
}
export default User;

现在在我的 React 组件中,我正在尝试实例化用户对象。

class Header extends React.Component {

    constructor(props) {
      super(props);
      this.state = { fullName: null, yguid: null };

    }
    componentWillMount(){
       user = getUserData(url);
       console.log(user);
       //set state with User data
    }

我的 React 组件中有以下导入语句。

import User from '../models/user';
import '../api/util';

我的用户和函数 getUserData 都未定义。我做错了什么,我该如何解决。提前致谢。

您的代码 user = getUserData(url) 正在为用户设置获取承诺。您还需要在那里设置解析器。我会这样写

componentWillMount(){
 let user; 
 // getUserData actually returns a promise. resolve with a .then and set user to result
getUserData(url).then((result) => {
 user = result;

 console.log(user); // user should be defined here

 // not sure if user is a state object or not but if it is set it like this
 this.setState({user: user})
 })
}