无法设置React组件的状态

时间:2016-11-03 05:41:24

标签: javascript reactjs fetch-api

我正在使用反应组件中的fetch API调用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不起作用。如果我在then块中的console.log(数据),它输出正确的数据,但在下一行失败。我怎样才能正确地做到这一点。

3 个答案:

答案 0 :(得分:3)

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

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

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

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

答案 1 :(得分:0)

这是因为您在this下使用的fetch与类this下的MyComponent不同。

尝试使用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);
  });

希望这有帮助!

答案 2 :(得分:0)

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

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