无法设置 React 组件的状态

Unable to set State of React Component

我正在调用 API 使用我的 React 组件中的提取 API 来设置状态。这是我的代码。

class MyComponent extends React.Component {

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

  }
  componentWillMount(){

    fetch(url)
      .then(
        function(response) {
          if (response.status !== 200) {
            console.log('Looks like there was a problem. Status Code: ' +
              response.status);
            return;
          }

          response.json().then(function(data) {
            this.setState( fullName = data.first.givenName + " " + data.lastName,
              uid =data.uid );
          });
        }
      )
      .catch(function(err) {
        console.log('Fetch Error :-S', err);
      });
  }


  render() {
    return (
      <div className="header">
        <nav className="navbar navbar-default navbar-fixed-top">
          <div className="navbar-header">
            <a className="navbar-brand" href="#"> {this.state.fullName}</a>
          </div>


          <div className="brand-right">
            <ul className="nav navbar-nav navbar-right">
              <li><a href="#">UID: {this.state.yguid} </a></li>
            </ul>
          </div>
        </nav>
      </div>
    );
  }
}

export default MyComponent;

我收到以下错误:

Uncaught (in promise) TypeError: Cannot read property 'setState' of undefined

我似乎无法理解为什么 setState 不起作用。如果 I console.log(data) 在 then 块内,它输出正确的数据,但在下一行中失败。我怎样才能正确地做到这一点。

发生这种情况是因为您在 fetch 下使用的 this 与 class MyComponent 下的 this 不同。

尝试使用arrow functions

fetch(url)
  .then((response) => {
    if (response.status !== 200) {
      console.log('Looks like there was a problem. Status Code: ' +
        response.status);
      return;
    }

    response.json().then((data) => {
      this.setState({
        fullName: data.first.givenName + " " + data.lastName,
        uid: data.uid,
      });
    });
  })
  .catch((err) => {
    console.log('Fetch Error :-S', err);
  });

希望对您有所帮助!

您在 then 中传递的函数未绑定到当前上下文,这导致您的回调函数中的 this 未定义,而不是引用您的组件实例。只需使用 bind(this) 将回调与组件绑定,如下所示:

.then(function () {
  // function body
}.bind(this));

或者您可以使用箭头函数,它隐式绑定上下文:

.then(() => {
  // function body
});

设置状态的正确方法是将状态作为对象传递。例如:

this.setState({
  fullName: data.first.givenName + " " + data.lastName,
  uid: data.uid
});