React this is undefined

↘锁芯ラ 提交于 2019-11-28 04:13:12

问题


React this is undefined in promise . Here is my code:

export default class Album extends React.Component {

    constructor(props) {
        super(props);
    }

    componentDidMount ()  {
        console.log(this.props.route.appState.tracks);  // `this` is working
        axios({
            method: 'get',
            url: '/api/album/' + this.props.params.id + '/' + 'tracks/',
            headers: {
                'Authorization': 'JWT ' + sessionStorage.getItem('token')
            }
        }).then(function (response) {
            console.log(response.data);
            this.props.route.appState.tracks.concat(response.data); // 'this' isn't working
        }).catch(function (response) {
            console.error(response);
            //sweetAlert("Oops!", response.data, "error");
        })
    }

here is the error code:

TypeError: this is undefined
Stack trace:
componentDidMount/<@webpack:///./static/apps/components/Album.jsx?:81:17

回答1:


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) )



回答2:


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

Other way: using arrow function




回答3:


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



来源:https://stackoverflow.com/questions/38238512/react-this-is-undefined

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