React this is undefined

我与影子孤独终老i 提交于 2019-11-29 10:51:30

Probably it's not binding this.

Try replacing with arrow functions if you're able to use ES6 syntax. It automatically binds this:

.then( (response) => {
        console.log(response.data);
        this.props.route.appState.tracks.concat(response.data); // 'this' isn't working
    } )

Or bind manually:

.then(function (response) {
            console.log(response.data);
            this.props.route.appState.tracks.concat(response.data);
        }.bind(this) )

You can bind this into thoes functions. Or you also declare self = this in componentDidMount function. then using self instand of this in axios

Example:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "My_Name"
    };
    this.componentDidMount = this.componentDidMount.bind(this);
  }

  componentDidMount () {
    let node = this.refs.term;
    term.focus();
  }

  render () {
    return (
      <div>
        <input type="text" ref="term" />
      </div>
    );
  }
}

or you can use this module auto-bind

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!